首页 > 编程语言 > 详细

Java多线程~~~使用信号量来控制资源获取

时间:2014-09-21 23:05:42      阅读:548      评论:0      收藏:0      [点我收藏+]

在多线程开发中,有一个很经典的名词,那就是信号量。信号量就是用来衡量一个资源的可利用数目的,根据信号

量的多少来控制在多线程中各个资源之间的冲突问题,在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多线程~~~使用信号量来控制资源获取

原文:http://blog.csdn.net/a352193394/article/details/39457107

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!