3线程同步实用程序
在这一节中,我们将讨论如何使用高级别机制去获得多线程的同步(synchronized)。这些高级别机制有下面几种:
? 信号(Semaphores):一个信号就是一个计数器,它控制着对于一个或者多个共享资源的访问。这个机制是并发编程的基本工具,在大多数编程语言中都提供这样的机制。
? 倒计时弹簧锁:CountDownLatch类是Java语言提供的一种机制,允许一个线程去等待多个操作行为的结束。
? 循环阻塞器:CyclicBarrier类是Java语言提供的一种机制,允许在一个普通点上同步多个线程。
? 分阶分离器(Phaser):Phaser类是Java API 7语言中提供的一种机制。它控制着并发程序在多个阶段来执行。这是Java API 7 中的新特性。
? 交换器(Exchanger):交换器类是Java语言提供的另外的机制,提供给两个线程一个交换数据点。
3.1 控制并发地访问一个资源
Semaphore类有两个 acquire()方法的另外版本:
1. acqureUninterruptibly():当这个内部的计数器的信号为0,阻塞这个线程直到这个信号被释放。在这个阻塞时间内,线程可能会被中断。然后,这个方法报出InterruptedException异常。这个版本的acquire将忽略掉线程的中断,不会报出任何异常。
2. tryAcqure():这个方法将尝试着获取信号(semaphore)。如果它获得了,这个方法返回true值。但是,如果它不能够,这个方法返回false值,而不会被阻塞并等待信号的释放。程序员负责根据这个返回值而定义正确的业务逻辑。
下面列举一个例子,说明semaphore的使用。例子中定义打印队列服务,多线程PrintJob调用打印服务。
定义PrintQueueTask类:
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* This class implements thePrintQueue using a Semaphore to control the
* access to it.
*
*/
public class PrintQueueTask {
/**
* Semaphore to control the access to the queue
*/
private finalSemaphore semaphore;
/**
* Constructor of the class. Initializes thesemaphore
*/
public PrintQueueTask(){
semaphore=new Semaphore(1);
}
/**
* Method that simulates printing a document
* @param document Document to print
*/
public voidprintJob (Object document){
try {
// Get the access to the semaphore. If other job is printing, this
// thread sleep until get the access to the semaphore
semaphore.acquire();
Long duration=(long)(Math.random()*5);
System.out.printf("%s: PrintQueuesTask: Printing a Job during %d seconds\n",Thread.currentThread().getName(),duration);
Thread.sleep(duration);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// Free the semaphore. If there are other threads waiting for thissemaphore,
// the JVM selects one of this threads and give it the access.
semaphore.release();
}
}
}
定义执行类PrintJob:
/**
* This class simulates a job thatsend a document to print.
*
*/
public class PrintJob implements Runnable {
/**
* Queue to print the documents
*/
private PrintQueueTask printQueueTask;
/**
* Constructor of the class. Initializes thequeue
* @param printQueueTask
*/
public PrintJob(PrintQueueTask printQueueTask){
this.printQueueTask=printQueueTask;
}
/**
* Core method of the Job. Sends the documentto the print queue and waits
* forits finalization
*/
@Override
public void run() {
System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName());
printQueueTask.printJob(new Object());
System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName());
}/**
* Main method of the class. Run ten jobs inparallel that
* send documents to the print queue at thesame time.
*/
public static void main (String args[]){
// Creates the print queue
PrintQueueTask printQueue=new PrintQueueTask();
// Creates ten Threads
Thread thread[]=new Thread[10];
for (int i=0; i<10; i++){
thread[i]=new Thread(new PrintJob(printQueue),"Thread "+i);
}
// Starts the Threads
for (int i=0; i<10; i++){
thread[i].start();
}
}
}
执行结果:
Thread0: Going to print a job
Thread9: Going to print a job
Thread8: Going to print a job
Thread7: Going to print a job
Thread6: Going to print a job
Thread5: Going to print a job
Thread4: Going to print a job
Thread3: Going to print a job
Thread2: Going to print a job
Thread1: Going to print a job
Thread0: PrintQueuesTask: Printing a Job during 1 seconds
Thread0: The document has been printed
Thread9: PrintQueuesTask: Printing a Job during 3 seconds
Thread9: The document has been printed
Thread8: PrintQueuesTask: Printing a Job during 4 seconds
Thread7: PrintQueuesTask: Printing a Job during 3 seconds
Thread8: The document has been printed
Thread7: The document has been printed
Thread6: PrintQueuesTask: Printing a Job during 2 seconds
Thread6: The document has been printed
Thread5: PrintQueuesTask: Printing a Job during 4 seconds
Thread5: The document has been printed
Thread4: PrintQueuesTask: Printing a Job during 2 seconds
Thread3: PrintQueuesTask: Printing a Job during 3 seconds
Thread4: The document has been printed
Thread3: The document has been printed
Thread2: PrintQueuesTask: Printing a Job during 0 seconds
Thread2: The document has been printed
Thread1: PrintQueuesTask: Printing a Job during 3 seconds
Thread 1: The document has been printed