Java多线程~~~使用信号量来控制资源获取
2014-09-21 22:00
330 查看
在多线程开发中,有一个很经典的名词,那就是信号量。信号量就是用来衡量一个资源的可利用数目的,根据信号
量的多少来控制在多线程中各个资源之间的冲突问题,在Java中也提供了对信号量的支持。
而且在创建信号量的时候,第二个参数用来指定采取何种分配策略,比如当有很多线程被阻塞,但有一个机会的时
候,信号量应该选择谁去运行呢,如果选择true,就采用公平模式,到时候看哪个线程等待的时间最久,就把机会给那
个等待最久的线程,这样的就是公平分配策略。
下面就用代码来说明一下问题
量的多少来控制在多线程中各个资源之间的冲突问题,在Java中也提供了对信号量的支持。
而且在创建信号量的时候,第二个参数用来指定采取何种分配策略,比如当有很多线程被阻塞,但有一个机会的时
候,信号量应该选择谁去运行呢,如果选择true,就采用公平模式,到时候看哪个线程等待的时间最久,就把机会给那
个等待最久的线程,这样的就是公平分配策略。
下面就用代码来说明一下问题
package com.bird.concursey.charpet4; import java.util.concurrent.Semaphore; public class PrintQueue { // It initializes the semaphore object that will protect the access from the // print queue. private final Semaphore semaphore = new Semaphore(1,true); public void printJob(Object document) { //you must acquire the semaphore calling try { semaphore.acquire(); long duration = (long)(Math.random()*10); System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n",Thread.currentThread().getName(),duration); Thread.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); }finally{ //free the semaphore by calling the release() method of the semaphore. semaphore.release(); } } }
package com.bird.concursey.charpet4; public class Job implements Runnable { private PrintQueue printQueue; public Job(PrintQueue printQueue) { this.printQueue = printQueue; } @Override public void run() { System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); printQueue.printJob(new Object()); System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); } public static void main(String[] args) { PrintQueue printQueue = new PrintQueue(); Thread thread[] = new Thread[10]; for(int i = 0; i < 10; i++) { thread[i] = new Thread(new Job(printQueue), "Thread " + i); } for(int i = 0; i < 10; i++) { thread[i].start(); } } }
相关文章推荐
- java多线程-Semaphore信号量使用 介绍 信号量(Semaphore),有时被称为信号灯,是在多线程环境下使用的一种设施, 它负责协调各个线程, 以保证它们能够正确、合理的使用公共资源
- java 使用StampedLock控制公共资源获取
- Java中的Semaphore--用于多线程中控制资源并发访问的线程数
- java TheadLocal 多线程资源使用
- 【Java多线程】使用Semaphore限制资源访问的线程数
- Java多线程学习笔记——信号量的使用
- C# 使用Semaphore(信号量)控制多线程
- [原]Java多线程编程学习笔记之六:使用synchronized获取互斥锁的几点说明
- Java基础-23总结多线程,线程实现Runnable接口,线程名字获取和设置,线程控制,线程安全,同步线程
- Java多线程学习笔记——信号量的使用
- Spring中使用UrlResource获取网络资源的时候报java.io.FileNotFoundException错误
- java多线程控制-信号量Semaphore
- java并发编程学习:用 Semaphore (信号量)控制并发资源
- java 中多线程和锁的使用以及获取多线程执行结果
- Java【多线程知识总结(6)】使用Runnable接口创建多线程,处理同一个资源
- 使用对象锁与多线程访问资源控制
- java多线程--信号量Semaphore的使用
- Java多线程之信号量(Semaphore)的使用
- JAVA多线程顺序执行(使用join,lock,condition,信号量)原理和java源代码
- JAVA之旅(十二)——Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口