标签:semaphore
本文是学习网络上的文章时的总结,感谢大家无私的分享。
当一个线程想要访问某个共享资源,首先,它必须获得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(); } } }
参考:
Java并发学习之十六——线程同步工具之信号量(Semaphores)
标签:semaphore
原文地址:http://blog.csdn.net/junshuaizhang/article/details/39553163