标签:oop condition import for nbsp cal lag 有序 pre
想让多个线程有序执行,必须提供它们之间的唤醒机制。下面以三个线程为例,有序打印自己的线程ID
Condition condition1 = lock.newCondition(); //代表线程1的唤醒
Condition condition2 = lock.newCondition(); //代表线程2的唤醒
Condition condition3= lock.newCondition(); //代表线程3的唤醒
同时需要一个Flag作为轮到它们各自执行的条件flag=1线程1执行,不等于1则线程1进入等待唤醒
代码:
1 package xianchengtest; 2 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.Lock; 5 import java.util.concurrent.locks.ReentrantLock; 6 7 public class TestABCAlternate { 8 9 public static void main(String[] args) { 10 ABCAlternate as = new ABCAlternate(); 11 new Thread(new Runnable() { 12 13 @Override 14 public void run() { 15 for (int i = 1; i <= 10 ;i++) { 16 as.loopA(i); 17 18 } 19 } 20 },"A").start(); 21 new Thread(new Runnable() { 22 23 @Override 24 public void run() { 25 for (int i = 1; i <= 10 ;i++) { 26 as.loopB(i); 27 28 } 29 } 30 },"B").start(); 31 new Thread(new Runnable() { 32 33 @Override 34 public void run() { 35 for (int i = 1; i <= 10 ;i++) { 36 as.loopC(i); 37 System.out.println("----------------------------------"); 38 } 39 } 40 },"C").start(); 41 42 } 43 44 } 45 46 class ABCAlternate{ 47 private int flag = 1; 48 private Lock lock = new ReentrantLock(); 49 private Condition condition1 = lock.newCondition(); 50 private Condition condition2 = lock.newCondition(); 51 private Condition condition3 = lock.newCondition(); 52 53 public void loopA(int totaloop) { 54 lock.lock(); 55 56 try { 57 //判断 58 if(flag != 1) { 59 try { 60 condition1.await(); 61 } catch (InterruptedException e) { 62 } 63 } 64 //打印 65 for (int i = 1; i <= 1; i++) { 66 System.out.println(Thread.currentThread().getName() +"\t"+ i+ "\t" + totaloop); 67 } 68 //唤醒 69 flag = 2 ; 70 condition2.signal(); 71 } finally { 72 lock.unlock(); 73 } 74 } 75 public void loopB(int totaloop) { 76 lock.lock(); 77 78 try { 79 //判断 80 if(flag != 2) { 81 try { 82 condition2.await(); 83 } catch (InterruptedException e) { 84 } 85 } 86 //打印 87 for (int i = 1; i <= 1; i++) { 88 System.out.println(Thread.currentThread().getName() +"\t"+ i+ "\t" + totaloop); 89 } 90 //唤醒 91 flag = 3 ; 92 condition3.signal(); 93 } finally { 94 lock.unlock(); 95 } 96 } 97 public void loopC(int totaloop) { 98 lock.lock(); 99 100 try { 101 //判断 102 if(flag != 3) { 103 try { 104 condition3.await(); 105 } catch (InterruptedException e) { 106 } 107 } 108 //打印 109 for (int i = 1; i <= 1; i++) { 110 System.out.println(Thread.currentThread().getName() +"\t"+ i+ "\t" + totaloop); 111 } 112 //唤醒 113 flag = 1 ; 114 condition1.signal(); 115 } finally { 116 lock.unlock(); 117 } 118 } 119 120 121 }
标签:oop condition import for nbsp cal lag 有序 pre
原文地址:https://www.cnblogs.com/blog-of-zxf/p/11126939.html