如果一个线程要访问一个共享资源,它必须先获得信号量。如果信号量的内部计数器大于0,信号量减1,然后允许访问这个共享资源。计数器大于0意味着有可以使用的资源,线程允许使用其中一个资源。
否则,如果信号量的计数器等于0,信号量将会把线程置入休眠直至计数器大于0,计数器等于0的时候意味着所有的共享资源已经被其他线程使用了,所以需要访问这个共享资源的线程必须等待。
当线程使用完某个共享资源时,信号量必须被释放,以便其他线程能够访问共享资源。释放操作将使信号量的内部计数器增加1。
资源: 打印队列
import java.util.concurrent.Semaphore;
/**
* Created by Administrator.
*/
public class PrintQueue {
private final Semaphore semaphore;
public PrintQueue(){
semaphore = new Semaphore(1);
}
public void printJob(Object document){
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{
semaphore.release();
System.out.printf("%s: Done the print job\n", Thread.currentThread().getName());
}
}
}
Runnable job:
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());
}
}
Main:
public class Main {
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();
}
}
}
用信号量来保护一个资源的多个副本。
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by Administrator.
*/
public class PrintQueue {
private final Semaphore semaphore;
private boolean freePrinters[];
private Lock lockPrinters;
public PrintQueue(){
semaphore = new Semaphore(3);
freePrinters=new boolean[3];
for(int i=0; i<3; i++){
freePrinters[i] = true;
}
lockPrinters=new ReentrantLock();
}
public void printJob(Object document){
try{
semaphore.acquire();
int assignedPrinter = getPrinter();
long duration = (long)(Math.random() * 10);
System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n", Thread.currentThread()
.getName(), assignedPrinter, duration
);
TimeUnit.SECONDS.sleep(duration);
freePrinters[assignedPrinter]=true;
}catch(InterruptedException e){
e.printStackTrace();
}finally{
semaphore.release();
System.out.printf("%s: Done the print job\n", Thread.currentThread().getName());
}
}
private int getPrinter(){
int ret = -1;
try{
lockPrinters.lock();
for(int i=0; i<freePrinters.length; i++){
if(freePrinters[i]){
ret = i;
freePrinters[i] = false;
break;
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
lockPrinters.unlock();
}
return ret;
}
}