并发基础知识2

本文深入探讨了线程的生命周期、中断机制、协作模式(如wait()、notify())、生产者-消费者模型、队列的应用、管道输入输出、死锁避免、CountDownLatch与CyclicBarrier的使用、以及Semaphore和Exchanger的特性。通过实例代码,展示了如何高效地管理和协调多线程任务,以解决并发编程中的常见问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

4终结任务
1、装饰性花园


2、在阻塞时终结
四种状态:
新建(new):当线程被创建时,他只会短暂的出于这种状态。
就绪(Runnable):在这种状态下,只要调度器把时间片分配给线程,线程就可以运行。
阻塞(Blocked):线程能够运行,但有某个条件阻止他的运行。
死亡(Dead):处于死亡活终止状态的线程将不再是可调度的,并且再也不会得到CPU时间,他的任务已经结束,或不再是可运行的。


进入阻塞状态:
一个任务进入阻塞状态可能有如下原因:
通过调用sleep(milliseconds)使任务进入休眠状态,在这种情况下,任务在指定的时间内不会运行。
你通过调用wait()使线程挂起。知道线程得到notify()或notifyAll()消息(或者在Java SE5中java.util.concurrent类库中等价的signal()或signalAll()消息),线程才会进入就绪状态。
任务在等待某个输入/输出完成。
任务试图在某个对象上调用其同步控制方法,但是对象锁不可用,因为另一个任务已经获得了这个锁。



3、中断
Thread.interrupt()或者新类库里面通过Executor的submit()来获得Future<?>返回值,这个Future提供cancel()以停止这个线程。

cancel:
boolean cancel(boolean mayInterruptIfRunning)试图取消对此任务的执行。如果任务已完成、或已取消,或者由于某些其他原因而无法取消,则此尝试将失败。当调用 cancel 时,如果调用成功,而此任务尚未启动,则此任务将永不运行。如果任务已经启动,则 mayInterruptIfRunning 参数确定是否应该以试图停止任务的方式来中断执行此任务的线程。

参数:
mayInterruptIfRunning - 如果应该中断执行此任务的线程,则为 true;否则允许正在运行的任务运行完成。
返回:
如果无法取消任务,则返回 false,这通常是由于它已经正常完成;否则返回 true。


被互斥所阻塞
如果你尝试着在一个对象上调用其synchronized方法,而这个对象的锁已经被其他任务获得,那么调用任务讲被挂起(阻塞),直至这个锁可获得。




4、检查中断
注意,当你在线程上调用interrupt()时,中断发生的唯一时刻是在任务要进入到阻塞操作中,或者已经在阻塞操作内部时。
如果你调用interrupt()以停止某个任务,那么在run()循环碰巧没有产生任何阻塞调用的情况下,你的任务将需要第二种方式退出。
还可以通过interrupted()来检测中断状态。









5线程之间的协作
1、wait()与notifyAll()
wait()使你可以等待某个条件发生变化,而改变这个条件超出了当前方法的控制能力。只有在notify()或notifyAll()发生时,这个任务才会被唤醒并且去检查所发生的变化。因此,wait()提供了一种在任务之间对活动同步的方式。
调用sleep()的时候锁并没有释放,调用yield()也属于这种情况。wait()将释放锁。
wait还可以指定时间参数。

Demo:
  1. packagecom.partner4java.tij.cooperate;
  2. publicclassCar {
  3. privatebooleanwaxOn =false;
  4. publicsynchronizedvoidwaxed(){
  5. waxOn =true;//Ready to buff
  6. notifyAll();
  7. }
  8. publicsynchronizedvoidbuffed(){
  9. waxOn =false;//Ready for another coat of wax
  10. notifyAll();
  11. }
  12. publicsynchronizedvoidwaitForWaxing()throwsInterruptedException{
  13. while(waxOn ==false)
  14. wait();
  15. }
  16. publicsynchronizedvoidwaitForBuffing()throwsInterruptedException{
  17. while(waxOn ==true)
  18. wait();
  19. }
  20. }
  21. packagecom.partner4java.tij.cooperate;
  22. importjava.util.concurrent.TimeUnit;
  23. publicclassWaxOffimplementsRunnable {
  24. privateCar car;
  25. publicWaxOff(Car c) {
  26. car = c;
  27. }
  28. @Override
  29. publicvoidrun() {
  30. try{
  31. while(!Thread.interrupted()){
  32. car.waitForWaxing();
  33. System.out.println("Wax Off!");
  34. TimeUnit.MILLISECONDS.sleep(200);
  35. car.buffed();
  36. }
  37. }catch(InterruptedException e) {
  38. System.out.println("Exiting via interrupt");
  39. }
  40. System.out.println("Ending Wax Off task");
  41. }
  42. }
  43. packagecom.partner4java.tij.cooperate;
  44. importjava.util.concurrent.TimeUnit;
  45. publicclassWaxOnimplementsRunnable {
  46. privateCar car;
  47. publicWaxOn(Car c) {
  48. car = c;
  49. }
  50. @Override
  51. publicvoidrun() {
  52. try{
  53. while(!Thread.interrupted()){
  54. System.out.println("Wax On!");
  55. TimeUnit.MILLISECONDS.sleep(200);
  56. car.waxed();
  57. car.waitForBuffing();
  58. }
  59. }catch(InterruptedException e) {
  60. System.out.println("Exiting via interrupt");
  61. }
  62. System.out.println("Ending Wax on Task");
  63. }
  64. }
  65. packagecom.partner4java.tij.cooperate;
  66. importjava.util.concurrent.ExecutorService;
  67. importjava.util.concurrent.Executors;
  68. importjava.util.concurrent.ThreadFactory;
  69. importjava.util.concurrent.TimeUnit;
  70. publicclassWaxOMatic {
  71. publicstaticvoidmain(String[] args)throwsInterruptedException {
  72. ExecutorService executorService = Executors.newCachedThreadPool(newThreadFactory() {
  73. @Override
  74. publicThread newThread(Runnable r) {
  75. Thread thread =newThread(r);
  76. thread.setDaemon(true);
  77. returnthread;
  78. }
  79. });
  80. Car car =newCar();
  81. executorService.execute(newWaxOff(car ));
  82. executorService.execute(newWaxOn(car));
  83. TimeUnit.SECONDS.sleep(5);
  84. executorService.shutdown();
  85. }
  86. }


错失信号:
解决方案是防止在变量上产生竞争条件。
  1. T1:
  2. synchronized(sharedMonitor){
  3. <setup conditionforT2>
  4. sharedMonitor.notify();
  5. }
  6. T2:
  7. synchronized(sharedMonitor){
  8. while(someCondition)
  9. sharedMonitor.wait();
  10. }





2、notify()与notifyAll()
使用notify不是notifyAll的一种优化。
当notifyAll因某个特定的锁而被调用时,只要等待这个锁的任务才会被唤醒。

Demo:
  1. packagecom.partner4java.tij.cooperate;
  2. publicclassBlocker {
  3. synchronizedvoidwaitCall(){
  4. try{
  5. while(!Thread.interrupted()){
  6. wait();
  7. System.out.println(Thread.currentThread() +" ");
  8. }
  9. }catch(Exception e) {
  10. }
  11. }
  12. synchronizedvoidprod(){
  13. notify();
  14. }
  15. synchronizedvoidprodAll(){
  16. notifyAll();
  17. }
  18. }
  19. packagecom.partner4java.tij.cooperate;
  20. publicclassTaskimplementsRunnable {
  21. staticBlocker blocker =newBlocker();
  22. @Override
  23. publicvoidrun() {
  24. blocker.waitCall();
  25. }
  26. }
  27. packagecom.partner4java.tij.cooperate;
  28. publicclassTask2implementsRunnable {
  29. staticBlocker blocker =newBlocker();
  30. @Override
  31. publicvoidrun() {
  32. blocker.waitCall();
  33. }
  34. }
  35. packagecom.partner4java.tij.cooperate;
  36. importjava.util.concurrent.ExecutorService;
  37. importjava.util.concurrent.Executors;
  38. importjava.util.concurrent.TimeUnit;
  39. publicclassNotifyVsNotifyAll {
  40. publicstaticvoidmain(String[] args)throwsInterruptedException {
  41. ExecutorService executorService = Executors.newCachedThreadPool();
  42. for(inti=0;i<5;i++){
  43. executorService.execute(newTask());
  44. }
  45. executorService.execute(newTask2());
  46. executorService.execute(newRunnable() {
  47. @Override
  48. publicvoidrun() {
  49. System.out.println("Task.blocker.prod");
  50. Task.blocker.prod();
  51. System.out.println("Task2.blocker.prodAll");
  52. Task2.blocker.prodAll();
  53. }
  54. });
  55. TimeUnit.MILLISECONDS.sleep(100);
  56. executorService.shutdownNow();
  57. }
  58. }





3、生产者和消费者
Demo:
  1. packagecom.partner4java.tij.cooperate;
  2. publicclassMeal {
  3. privatefinalintorderNum;
  4. publicMeal(intorderNum) {
  5. this.orderNum = orderNum;
  6. }
  7. @Override
  8. publicString toString() {
  9. return"Meal [orderNum="+ orderNum +"]";
  10. }
  11. }
  12. packagecom.partner4java.tij.cooperate;
  13. publicclassWaitPersonimplementsRunnable {
  14. privateRestaurant restaurant;
  15. publicWaitPerson(Restaurant restaurant) {
  16. this.restaurant = restaurant;
  17. }
  18. @Override
  19. publicvoidrun() {
  20. try{
  21. while(!Thread.interrupted()){
  22. synchronized(this) {
  23. while(restaurant.meal ==null){
  24. wait();
  25. }
  26. }
  27. System.out.println("Waitperson got "+ restaurant.meal);
  28. synchronized(restaurant.chef) {
  29. restaurant.meal =null;
  30. restaurant.chef.notifyAll();//Ready for another
  31. }
  32. }
  33. }catch(InterruptedException e) {
  34. System.out.println("WaitPerson interrupted");
  35. }
  36. }
  37. }
  38. packagecom.partner4java.tij.cooperate;
  39. importjava.util.concurrent.TimeUnit;
  40. publicclassChefimplementsRunnable {
  41. privateRestaurant restaurant;
  42. privateintcount =0;
  43. publicChef(Restaurant restaurant) {
  44. this.restaurant = restaurant;
  45. }
  46. @Override
  47. publicvoidrun() {
  48. try{
  49. while(!Thread.interrupted()){
  50. synchronized(this) {
  51. while(restaurant.meal !=null){
  52. wait();
  53. }
  54. }
  55. if(++count ==10){
  56. System.out.println("Out of food,closing");
  57. restaurant.exec.shutdownNow();
  58. }
  59. System.out.println("Order up!");
  60. synchronized(restaurant.waitPerson) {
  61. restaurant.meal =newMeal(count);
  62. restaurant.waitPerson.notifyAll();
  63. }
  64. TimeUnit.MILLISECONDS.sleep(100);
  65. }
  66. }catch(InterruptedException e) {
  67. System.out.println("Chef interrupted");
  68. }
  69. }
  70. }
  71. packagecom.partner4java.tij.cooperate;
  72. importjava.util.concurrent.ExecutorService;
  73. importjava.util.concurrent.Executors;
  74. publicclassRestaurant {
  75. Meal meal;
  76. ExecutorService exec = Executors.newCachedThreadPool();
  77. WaitPerson waitPerson =newWaitPerson(this);
  78. Chef chef =newChef(this);
  79. publicRestaurant() {
  80. exec.execute(chef);
  81. exec.execute(waitPerson);
  82. }
  83. publicstaticvoidmain(String[] args) {
  84. newRestaurant();
  85. }
  86. }



使用显示的Lock和Condition对象:
Demo:
  1. classBoundedBuffer {
  2. finalLock lock =newReentrantLock();
  3. finalCondition notFull= lock.newCondition();
  4. finalCondition notEmpty = lock.newCondition();
  5. finalObject[] items =newObject[100];
  6. intputptr, takeptr, count;
  7. publicvoidput(Object x)throwsInterruptedException {
  8. lock.lock();
  9. try{
  10. while(count == items.length)
  11. notFull.await();
  12. items[putptr] = x;
  13. if(++putptr == items.length) putptr =0;
  14. ++count;
  15. notEmpty.signal();
  16. }finally{
  17. lock.unlock();
  18. }
  19. }
  20. publicObject take()throwsInterruptedException {
  21. lock.lock();
  22. try{
  23. while(count ==0)
  24. notEmpty.await();
  25. Object x = items[takeptr];
  26. if(++takeptr == items.length) takeptr =0;
  27. --count;
  28. notFull.signal();
  29. returnx;
  30. }finally{
  31. lock.unlock();
  32. }
  33. }
  34. }






4、生产者-消费者与队列
使用同步队列来解决任务协作问题。同步队列在任务时刻都只允许一个任务插入或移除元素。
Demo:
  1. packagecom.partner4java.tij.blockingqueue;
  2. importjava.util.concurrent.BlockingQueue;
  3. importcom.partner4java.tij.util.LiftOff;
  4. publicclassLiftOffRunnerimplementsRunnable {
  5. privateBlockingQueue<LiftOff> rockets;
  6. publicLiftOffRunner(BlockingQueue<LiftOff> rockets) {
  7. this.rockets = rockets;
  8. }
  9. publicvoidadd(LiftOff liftOff){
  10. try{
  11. rockets.add(liftOff);
  12. }catch(Exception e) {
  13. System.out.println("Interrupted during put()");
  14. }
  15. }
  16. @Override
  17. publicvoidrun() {
  18. try{
  19. while(!Thread.interrupted()){
  20. LiftOff liftOff = rockets.take();
  21. liftOff.run();
  22. }
  23. }catch(InterruptedException e) {
  24. System.out.println("Waking from take()");
  25. }
  26. System.out.println("Exiting LiftOffRunner");
  27. }
  28. }
  29. packagecom.partner4java.tij.blockingqueue;
  30. importjava.util.concurrent.ArrayBlockingQueue;
  31. importjava.util.concurrent.BlockingQueue;
  32. importjava.util.concurrent.LinkedBlockingDeque;
  33. importjava.util.concurrent.SynchronousQueue;
  34. importjava.util.concurrent.TimeUnit;
  35. importcom.partner4java.tij.util.LiftOff;
  36. publicclassTestBlockingQueues {
  37. publicstaticvoidmain(String[] args)throwsInterruptedException {
  38. test("LinkedBlockingQueue",newLinkedBlockingDeque<LiftOff>());
  39. test("ArrayBlockingQueue",newArrayBlockingQueue<LiftOff>(3));
  40. test("SynchronousQueue",newSynchronousQueue<LiftOff>());
  41. }
  42. privatestaticvoidtest(String message,BlockingQueue<LiftOff> rockets)throwsInterruptedException {
  43. System.out.println("test:"+ message);
  44. LiftOffRunner liftOffRunner =newLiftOffRunner(rockets);
  45. Thread thread =newThread(liftOffRunner);
  46. thread.start();
  47. for(inti=0;i<5;i++){
  48. liftOffRunner.add(newLiftOff(6));
  49. }
  50. thread.interrupt();
  51. }
  52. }
  53. //支持两个附加操作的 Queue,这两个操作是:检索元素时等待队列变为非空,以及存储元素时等待空间变得可用。
  54. //
  55. //BlockingQueue 不接受 null 元素。试图 add、put 或 offer 一个 null 元素时,某些实现会抛出 NullPointerException。null 被用作指示 poll 操作失败的警戒值。
  56. //
  57. //BlockingQueue 可以是限定容量的。它在任意给定时间都可以有一个 remainingCapacity,超出此容量,便无法无阻塞地 put 额外的元素。没有任何内部容量约束的 BlockingQueue 总是报告 Integer.MAX_VALUE 的剩余容量。
  58. //
  59. //BlockingQueue 实现主要用于生产者-使用者队列,但它另外还支持 Collection 接口。因此,举例来说,使用 remove(x) 从队列中移除任意一个元素是有可能的。然而,这种操作通常不 会有效执行,只能有计划地偶尔使用,比如在取消排队信息时。
  60. //
  61. //BlockingQueue 实现是线程安全的。所有排队方法都可以使用内部锁定或其他形式的并发控制来自动达到它们的目的。然而,大量的 Collection 操作(addAll、containsAll、retainAll 和 removeAll)没有 必要自动执行,除非在实现中特别说明。因此,举例来说,在只添加了 c 中的一些元素后,addAll(c) 有可能失败(抛出一个异常)。
  62. //
  63. //BlockingQueue 实质上不 支持使用任何一种“close”或“shutdown”操作来指示不再添加任何项。这种功能的需求和使用有依赖于实现的倾向。例如,一种常用的策略是:对于生产者,插入特殊的 end-of-stream 或 poison 对象,并根据使用者获取这些对象的时间来对它们进行解释。
  64. //
  65. //以下是基于典型的生产者-使用者场景的一个用例。注意,BlockingQueue 可以安全地与多个生产者和多个使用者一起使用。
  66. //
  67. // class Producer implements Runnable {
  68. // private final BlockingQueue queue;
  69. // Producer(BlockingQueue q) { queue = q; }
  70. // public void run() {
  71. // try {
  72. // while(true) { queue.put(produce()); }
  73. // } catch (InterruptedException ex) { ... handle ...}
  74. // }
  75. // Object produce() { ... }
  76. // }
  77. //
  78. // class Consumer implements Runnable {
  79. // private final BlockingQueue queue;
  80. // Consumer(BlockingQueue q) { queue = q; }
  81. // public void run() {
  82. // try {
  83. // while(true) { consume(queue.take()); }
  84. // } catch (InterruptedException ex) { ... handle ...}
  85. // }
  86. // void consume(Object x) { ... }
  87. // }
  88. //
  89. // class Setup {
  90. // void main() {
  91. // BlockingQueue q = new SomeQueueImplementation();
  92. // Producer p = new Producer(q);
  93. // Consumer c1 = new Consumer(q);
  94. // Consumer c2 = new Consumer(q);
  95. // new Thread(p).start();
  96. // new Thread(c1).start();
  97. // new Thread(c2).start();
  98. // }
  99. // }


当你存在多个任务之间的协调时,你还可以同时创建多个BlockingQueue,用于每个步骤的协调。





5、任务间使用管道进行输入/输出
Demo:
  1. packagecom.partner4java.tij.piped;
  2. importjava.io.IOException;
  3. importjava.io.PipedWriter;
  4. importjava.util.Random;
  5. importjava.util.concurrent.TimeUnit;
  6. publicclassSenderimplementsRunnable {
  7. privateRandom random =newRandom(47);
  8. privatePipedWriter out =newPipedWriter();
  9. publicPipedWriter getPipedWriter(){
  10. returnout;
  11. }
  12. @Override
  13. publicvoidrun() {
  14. try{
  15. while(true){
  16. for(charc ='A';c<='z';c++){
  17. out.write(c);
  18. TimeUnit.MILLISECONDS.sleep(random.nextInt(500));
  19. }
  20. }
  21. }catch(IOException e) {
  22. e.printStackTrace();
  23. }catch(InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. }
  27. }
  28. packagecom.partner4java.tij.piped;
  29. importjava.io.IOException;
  30. importjava.io.PipedReader;
  31. publicclassReceiverimplementsRunnable {
  32. privatePipedReader in;
  33. publicReceiver(Sender sender)throwsIOException {
  34. in =newPipedReader(sender.getPipedWriter());
  35. }
  36. @Override
  37. publicvoidrun() {
  38. try{
  39. while(true){
  40. System.out.println("Read:"+ (char)in.read()+",");
  41. }
  42. }catch(IOException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47. packagecom.partner4java.tij.piped;
  48. importjava.io.IOException;
  49. importjava.util.concurrent.ExecutorService;
  50. importjava.util.concurrent.Executors;
  51. importjava.util.concurrent.TimeUnit;
  52. publicclassPipedIO {
  53. publicstaticvoidmain(String[] args)throwsIOException, InterruptedException {
  54. Sender sender =newSender();
  55. Receiver receiver =newReceiver(sender);
  56. ExecutorService executorService = Executors.newCachedThreadPool();
  57. executorService.execute(sender);
  58. executorService.execute(receiver);
  59. TimeUnit.SECONDS.sleep(10);
  60. executorService.shutdownNow();
  61. }
  62. }







6死锁
某个任务在等待另一个任务,而后者又等待别的任务,这样一直下去,直到这个链条上的任务又在等待第一个任务释放锁,这样就造成了一个互相等待的循环。变成了死锁。

以下四个条件同时满足时,就会发生死锁:
1、互斥条件。
2、至少有一个任务他必须持有一个资源且正在等待获取一个当前被别的任务持有的资源。
3、资源不能被任务抢占,任务必须把资源释放当做普通事件。
4、必须有循环等待,这样,一个任务等待其他任务所持有的资源。







7新类库中的构件
1、CountDownLatch
他被也拿过来同步一个或多个任务,强制他们等待由其他任务执行的一组操作完成。
你可以向CountDownLatch对象设置一个初始计数值,任务在这个对象上调用wait()的方法都将阻塞,直至这个计数值到达0。
其他任务在结束起工作时,可以在改对象上调用countDown()来减小这个计数值。
CountDownLatch被设计为止触发一次,计数值不能被重置。如果你需要能够重置计数值的版本,则可以使用CyclicBarrier。
Demo:
package com.partner4java.tij.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class TaskPortion implements Runnable {
private static int count = 0;
private static final int id = count++;
private CountDownLatch countDownLatch;
public TaskPortion(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
dowork();
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private void dowork() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(this + " is completed");
}

@Override
public String toString() {
return "TaskPortion id:" + id;
}



}


package com.partner4java.tij.countdownlatch;

import java.util.concurrent.CountDownLatch;

public class WaitingTask implements Runnable {
private static int count = 0;
private static final int id = count++;
private CountDownLatch countDownLatch;

public WaitingTask(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}

@Override
public void run() {
try {
countDownLatch.await();
System.out.println("CountDownLatch barrier passed for " + this);
} catch (InterruptedException e) {
System.out.println(this + " interrupted");
}
}

@Override
public String toString() {
return "WaitingTask " + id;
}
}


package com.partner4java.tij.countdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {
private static final int SIZE = 100;

public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(SIZE);
for(int i=0;i<10;i++){
executorService.execute(new WaitingTask(countDownLatch));
}
for(int i=0;i<SIZE;i++){
executorService.execute(new TaskPortion(countDownLatch));
}
System.out.println("Launched all tasks");
executorService.shutdown();
}

}




类库的线程安全:







2、CyclicBarrier
CountDownLatch是只触发一次的事件,而CyclicBarrier可以多次重用。
一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时 CyclicBarrier 很有用。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。
CyclicBarrier 支持一个可选的 Runnable 命令,在一组线程中的最后一个线程到达之后(但在释放所有线程之前),该命令只在每个屏障点运行一次。若在继续所有参与线程之前更新共享状态,此屏障操作 很有用。

Demo:
  1. packagecom.partner4java.tij.se5.cyclicbarrier;
  2. importjava.util.Random;
  3. importjava.util.concurrent.BrokenBarrierException;
  4. importjava.util.concurrent.CyclicBarrier;
  5. publicclassHorseimplementsRunnable {
  6. privatestaticintcounter =0;
  7. privatestaticfinalintid = counter++;
  8. privateintstrides =0;
  9. privatestaticRandom random =newRandom(47);
  10. privatestaticCyclicBarrier barrier;
  11. publicHorse(CyclicBarrier barrier) {
  12. this.barrier = barrier;
  13. }
  14. publicsynchronizedintgetStrides() {
  15. returnstrides;
  16. }
  17. @Override
  18. publicvoidrun() {
  19. try{
  20. while(!Thread.interrupted()){
  21. synchronized(this) {
  22. strides += random.nextInt(3);
  23. }
  24. barrier.await();
  25. }
  26. }catch(InterruptedException e) {
  27. e.printStackTrace();
  28. }catch(BrokenBarrierException e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. @Override
  33. publicString toString() {
  34. return"Horse: "+ id;
  35. }
  36. publicString tracks() {
  37. StringBuilder builder =newStringBuilder();
  38. for(inti=0;i<getStrides();i++){
  39. builder.append("*");
  40. }
  41. builder.append(id);
  42. returnbuilder.toString();
  43. }
  44. }
  45. packagecom.partner4java.tij.se5.cyclicbarrier;
  46. importjava.util.ArrayList;
  47. importjava.util.List;
  48. importjava.util.concurrent.CyclicBarrier;
  49. importjava.util.concurrent.ExecutorService;
  50. importjava.util.concurrent.Executors;
  51. importjava.util.concurrent.TimeUnit;
  52. publicclassHorseRace {
  53. staticfinalintFINISH_LINE =75;
  54. privateList<Horse> horses =newArrayList<Horse>();
  55. privateExecutorService executorService = Executors.newCachedThreadPool();
  56. privateCyclicBarrier barrier;
  57. publicHorseRace(intnHorses,finalintpause) {
  58. barrier =newCyclicBarrier(nHorses,newRunnable() {
  59. @Override
  60. publicvoidrun() {
  61. StringBuilder builder =newStringBuilder();
  62. for(inti=0;i<FINISH_LINE;i++){
  63. builder.append("=");
  64. }
  65. System.out.println(builder);
  66. for(Horse horse:horses){
  67. System.out.println(horse.tracks());
  68. }
  69. for(Horse horse:horses){
  70. if(horse.getStrides() >= FINISH_LINE){
  71. System.out.println(horse +" won!");
  72. executorService.shutdownNow();
  73. return;
  74. }
  75. }
  76. try{
  77. TimeUnit.MILLISECONDS.sleep(pause);
  78. }catch(InterruptedException e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. });
  83. for(inti=0;i<nHorses;i++){
  84. Horse horse =newHorse(barrier);
  85. horses.add(horse);
  86. executorService.execute(horse);
  87. }
  88. }
  89. publicstaticvoidmain(String[] args) {
  90. intnHorses =7;
  91. intpause =200;
  92. newHorseRace(nHorses, pause);
  93. }
  94. }
  95. //一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point)。在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时 CyclicBarrier 很有用。因为该 barrier 在释放等待线程后可以重用,所以称它为循环 的 barrier。
  96. //
  97. //CyclicBarrier 支持一个可选的 Runnable 命令,在一组线程中的最后一个线程到达之后(但在释放所有线程之前),该命令只在每个屏障点运行一次。若在继续所有参与线程之前更新共享状态,此屏障操作 很有用。
  98. //
  99. //示例用法:下面是一个在并行分解设计中使用 barrier 的例子:
  100. //
  101. // class Solver {
  102. // final int N;
  103. // final float[][] data;
  104. // final CyclicBarrier barrier;
  105. //
  106. // class Worker implements Runnable {
  107. // int myRow;
  108. // Worker(int row) { myRow = row; }
  109. // public void run() {
  110. // while (!done()) {
  111. // processRow(myRow);
  112. //
  113. // try {
  114. // barrier.await();
  115. // } catch (InterruptedException ex) {
  116. //return;
  117. // } catch (BrokenBarrierException ex) {
  118. //return;
  119. // }
  120. // }
  121. // }
  122. // }
  123. //
  124. // public Solver(float[][] matrix) {
  125. // data = matrix;
  126. // N = matrix.length;
  127. // barrier = new CyclicBarrier(N,
  128. // new Runnable() {
  129. // public void run() {
  130. // mergeRows(...);
  131. // }
  132. // });
  133. // for (int i = 0; i < N; ++i)
  134. // new Thread(new Worker(i)).start();
  135. //
  136. // waitUntilDone();
  137. // }
  138. // }
  139. // 在这个例子中,每个 worker 线程处理矩阵的一行,在处理完所有的行之前,该线程将一直在屏障处等待。处理完所有的行之后,将执行所提供的 Runnable 屏障操作,并合并这些行。如果合并者确定已经找到了一个解决方案,那么 done() 将返回 true,所有的 worker 线程都将终止。
  140. //如果屏障操作在执行时不依赖于正挂起的线程,则线程组中的任何线程在获得释放时都能执行该操作。为方便此操作,每次调用 await() 都将返回能到达屏障处的线程的索引。然后,您可以选择哪个线程应该执行屏障操作,例如:
  141. //
  142. //if (barrier.await() == 0) {
  143. // // log the completion of this iteration
  144. // }对于失败的同步尝试,CyclicBarrier 使用了一种快速失败的、要么全部要么全不 (all-or-none) 的破坏模式:如果因为中断、失败或者超时等原因,导致线程过早地离开了屏障点,那么其他所有线程(甚至是那些尚未从以前的 await() 中恢复的线程)也将通过 BrokenBarrierException(如果它们几乎同时被中断,则用 InterruptedException)以反常的方式离开。











3、DelayQueue
这是一个无界的BlockingQueue,有您关于防止实现了Delayed接口的对象,其中的对象只能在其到期时才能从队列中取走。这种队列是有序的,即对头对象的延迟到期时间最长。如果没有任何延迟到期,那么就不会有任何头元素,并且poll()将返回null。


public class DelayQueue<E extends Delayed>extends AbstractQueue<E>implements BlockingQueue<E>Delayed 元素的一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的头部 是延迟期满后保存时间最长的 Delayed 元素。如果延迟都还没有期满,则队列没有头部,并且 poll 将返回 null。当一个元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回一个小于或等于零的值时,则出现期满。此队列不允许使用 null 元素。

此类及其迭代器实现了 Collection 和 Iterator 接口的所有可选 方法。

此类是 Java Collections Framework 的成员。



4、PriorityBlockingQueue
这是一个很基础的优先级队列,他具有可阻塞的读取操作。

public class PriorityBlockingQueue<E>extends AbstractQueue<E>implements BlockingQueue<E>, Serializable一个无界的阻塞队列,它使用与类 PriorityQueue 相同的顺序规则,并且提供了阻塞检索的操作。虽然此队列逻辑上是无界的,但是由于资源被耗尽,所以试图执行添加操作可能会失败(导致 OutOfMemoryError)。此类不允许使用 null 元素。依赖自然顺序的优先级队列也不允许插入不可比较的对象(因为这样做会抛出 ClassCastException)。

此类及其迭代器可以实现 Collection 和 Iterator 接口的所有可选 方法。iterator() 方法中所提供的迭代器并不 保证以特定的顺序遍历 PriorityBlockingQueue 的元素。如果需要有序地遍历,则应考虑使用 Arrays.sort(pq.toArray())。

此类是 Java Collections Framework 的成员。






5、使用ScheduledExecutor的温室控制器
public interface ScheduledExecutorServiceextends ExecutorService一个 ExecutorService,可安排在给定的延迟后运行或定期执行的命令。

schedule 方法使用各种延迟创建任务,并返回一个可用于取消或检查执行的任务对象。scheduleAtFixedRate 和 scheduleWithFixedDelay 方法创建并执行某些在取消前一直定期运行的任务。

用 Executor.execute(java.lang.Runnable) 和 ExecutorService 的 submit 方法所提交的命令,通过所请求的 0 延迟进行安排。schedule 方法中允许出现 0 和负数延迟(但不是周期),并将这些视为一种立即执行的请求。

所有的 schedule 方法都接受相对 延迟和周期作为参数,而不是绝对的时间或日期。将以 Date 所表示的绝对时间转换成要求的形式很容易。例如,要安排在某个以后的日期运行,可以使用:schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)。但是要注意,由于网络时间同步协议、时钟漂移或其他因素的存在,因此相对延迟的期满日期不必与启用任务的当前 Date 相符。 Executors 类为此包中所提供的 ScheduledExecutorService 实现提供了便捷的工厂方法。

用法示例
以下是一个带方法的类,它设置了 ScheduledExecutorService ,在 1 小时内每 10 秒钟蜂鸣一次:
  1. importstaticjava.util.concurrent.TimeUnit.*;
  2. classBeeperControl {
  3. privatefinalScheduledExecutorService scheduler =
  4. Executors.newScheduledThreadPool(1);
  5. publicvoidbeepForAnHour() {
  6. finalRunnable beeper =newRunnable() {
  7. publicvoidrun() { System.out.println("beep"); }
  8. };
  9. finalScheduledFuture<?> beeperHandle =
  10. scheduler.scheduleAtFixedRate(beeper,10,10, SECONDS);
  11. scheduler.schedule(newRunnable() {
  12. publicvoidrun() { beeperHandle.cancel(true); }
  13. },60*60, SECONDS);
  14. }
  15. }






6、Semaphore
正常的锁(来自concurrent.locks或内建的synchronized锁)在任何时刻都只允许一个任务访问一项资源,而计数信号量允许N个任务同时访问这个资源。你还可以将信号量看做是向外分发使用资源的的“许可证”,尽管实际上没有任何许可证对象。
public class Semaphoreextends Objectimplements Serializable一个计数信号量。从概念上讲,信号量维护了一个许可集合。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。

Semaphore 通常用于限制可以访问某些资源(物理或逻辑的)的线程数目。例如,下面的类使用信号量控制对内容池的访问:

  1. classPool {
  2. privatestaticfinalMAX_AVAILABLE =100;
  3. privatefinalSemaphore available =newSemaphore(MAX_AVAILABLE,true);
  4. publicObject getItem()throwsInterruptedException {
  5. available.acquire();
  6. returngetNextAvailableItem();
  7. }
  8. publicvoidputItem(Object x) {
  9. if(markAsUnused(x))
  10. available.release();
  11. }
  12. // Not a particularly efficient data structure; just for demo
  13. protectedObject[] items = ... whatever kinds of items being managed
  14. protectedboolean[] used =newboolean[MAX_AVAILABLE];
  15. protectedsynchronizedObject getNextAvailableItem() {
  16. for(inti =0; i < MAX_AVAILABLE; ++i) {
  17. if(!used[i]) {
  18. used[i] =true;
  19. returnitems[i];
  20. }
  21. }
  22. returnnull;// not reached
  23. }
  24. protectedsynchronizedbooleanmarkAsUnused(Object item) {
  25. for(inti =0; i < MAX_AVAILABLE; ++i) {
  26. if(item == items[i]) {
  27. if(used[i]) {
  28. used[i] =false;
  29. returntrue;
  30. }else
  31. returnfalse;
  32. }
  33. }
  34. returnfalse;
  35. }
  36. }

获得一项前,每个线程必须从信号量获取许可,从而保证可以使用该项。该线程结束后,将项返回到池中并将许可返回到该信号量,从而允许其他线程获取该项。注意,调用 acquire() 时无法保持同步锁定,因为这会阻止将项返回到池中。信号量封装所需的同步,以限制对池的访问,这同维持该池本身一致性所需的同步是分开的。

将信号量初始化为 1,使得它在使用时最多只有一个可用的许可,从而可用作一个相互排斥的锁。这通常也称为二进制信号量,因为它只能有两种状态:一个可用的许可,或零个可用的许可。按此方式使用时,二进制信号量具有某种属性(与很多 Lock 实现不同),即可以由线程释放“锁定”,而不是由所有者(因为信号量没有所有权的概念)。在某些专门的上下文(如死锁恢复)中这会很有用。

此类的构造方法可选地接受一个公平 参数。当设置为 false 时,此类不对线程获取许可的顺序做任何保证。特别地,闯入 是允许的,也就是说可以在已经等待的线程前为调用 acquire() 的线程分配一个许可,从逻辑上说,就是新线程将自己置于等待线程队列的头部。当公平设置为 true 时,信号量保证对于任何调用 acquire 方法的线程而言,都按照处理它们调用这些方法的顺序(即先进先出;FIFO)来选择线程、获得许可。注意,FIFO 排序必然应用到这些方法内的指定内部执行点。所以,可能某个线程先于另一个线程调用了 acquire,但是却在该线程之后到达排序点,并且从方法返回时也类似。还要注意,非同步的 tryAcquire 方法不使用公平设置,而是使用任意可用的许可。

通常,应该将用于控制资源访问的信号量初始化为公平的,以确保所有线程都可访问资源。为其他的种类的同步控制使用信号量时,非公平排序的吞吐量优势通常要比公平考虑更为重要。

此类还提供便捷的方法来同时 acquire 和 release 多个许可。小心,在未将公平设置为 true 时使用这些方法会增加不确定延期的风险。





7、Exchanger
Exchanger是两个对象之间交换对象的栅栏。当这些任务进入栅栏时,他们各自拥有一个对象,当他们离开时,他们都拥有之前由对象持有的对象。
public class Exchanger<V>extends Object两个线程可以交换对象的同步点。每个线程都在进入 exchange 方法时给出某个对象,并接受其他线程返回时给出的对象。

用法示例:以下是重点介绍的一个类,该类使用 Exchanger 在线程间交换缓冲区,因此,在需要时,填充缓冲区的线程获得一个新腾空的缓冲区,并将填满的缓冲区传递给腾空缓冲区的线程。
  1. classFillAndEmpty {
  2. Exchanger<DataBuffer> exchanger =newExchanger();
  3. DataBuffer initialEmptyBuffer = ... a made-up type
  4. DataBuffer initialFullBuffer = ...
  5. classFillingLoopimplementsRunnable {
  6. publicvoidrun() {
  7. DataBuffer currentBuffer = initialEmptyBuffer;
  8. try{
  9. while(currentBuffer !=null) {
  10. addToBuffer(currentBuffer);
  11. if(currentBuffer.full())
  12. currentBuffer = exchanger.exchange(currentBuffer);
  13. }
  14. }catch(InterruptedException ex) { ... handle ... }
  15. }
  16. }
  17. classEmptyingLoopimplementsRunnable {
  18. publicvoidrun() {
  19. DataBuffer currentBuffer = initialFullBuffer;
  20. try{
  21. while(currentBuffer !=null) {
  22. takeFromBuffer(currentBuffer);
  23. if(currentBuffer.empty())
  24. currentBuffer = exchanger.exchange(currentBuffer);
  25. }
  26. }catch(InterruptedException ex) { ... handle ...}
  27. }
  28. }
  29. voidstart() {
  30. newThread(newFillingLoop()).start();
  31. newThread(newEmptyingLoop()).start();
  32. }
  33. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值