在多线程开发中,有一个很经典的名词,那就是信号量。信号量就是用来衡量一个资源的可利用数目的,根据信号
量的多少来控制在多线程中各个资源之间的冲突问题,在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(); } } }
原文:http://blog.csdn.net/a352193394/article/details/39457107