Java并发学习之十六——线程同步工具之信号量(Semaphores)

本文是学习网络上的文章时的总结,感谢大家无私的分享。

当一个线程想要访问某个共享资源,首先,它必须获得semaphore。如果semaphore的内部计数器的值大于0,那么semaphore减少计数器的值并允许访问共享的资源。计数器的值大于0表示,有可以自由使用的资源,所以线程可以访问并使用它们。

package chapter3;

import java.util.concurrent.Semaphore;

public class PrintQueue2 {
	private final Semaphore semaphore;
	public PrintQueue2(){
		semaphore = new Semaphore(1);
				
	}
	public void printJob(Object document){
		
		try {
			semaphore.acquire();
			long duration = (long)(Math.random()*10);
			System.out.println(Thread.currentThread().getName()+"  PrintQueue   "+duration
					);
		} catch (InterruptedException e) {
			e.printStackTrace();
			
		}finally{
			semaphore.release();
		}
	}
}

package chapter3;

public class Job implements Runnable{
	private PrintQueue2 printQueue;
	public Job(PrintQueue2 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());
	}
}

package chapter3;

public class Main {

	/**
	 * <p>
	 * </p>
	 * @author zhangjunshuai
	 * @date 2014-9-23 下午8:45:31
	 * @param args
	 */
	public static void main(String[] args) {
		PrintQueue2 printQueue = new PrintQueue2();
		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();
		}
	}

}

可修改Semaphores的公平性,在默认的情况下信号量的进入是不公平的。如果在初始化的第二个参数设定为true时,则会选择时间等待最久的一个进入。

参考:

并发网

老紫竹并发学习

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值