Condition实现多对多交替打印:
1 import java.util.concurrent.locks.Condition; 2 import java.util.concurrent.locks.ReentrantLock; 3 4 /** 5 * 生产者消费者逻辑 6 */ 7 public class MyService { 8 9 private ReentrantLock lock = new ReentrantLock(); 10 private Condition condition = lock.newCondition(); 11 private boolean hasValue = false; 12 13 public void set() { 14 try { 15 lock.lock(); 16 while (hasValue) { 17 System.out.println("有可能☆☆连续"); 18 condition.await(); 19 } 20 System.out.println("☆"); 21 hasValue = true; 22 condition.signalAll(); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 }finally { 26 lock.unlock(); 27 } 28 } 29 30 public void get() { 31 try { 32 lock.lock(); 33 while(!hasValue) { 34 System.out.println("有可能★★连续"); 35 condition.await(); 36 } 37 System.out.println("★"); 38 hasValue = false; 39 condition.signalAll(); 40 } catch (InterruptedException e) { 41 e.printStackTrace(); 42 }finally { 43 lock.unlock(); 44 } 45 } 46 }
1 /** 2 * 生产者线程 3 */ 4 public class MyThreadA extends Thread{ 5 private MyService service; 6 7 public MyThreadA(MyService service) { 8 this.service = service; 9 } 10 11 @Override 12 public void run() { 13 for (int i = 0; i < Integer.MAX_VALUE; i++) { 14 service.set(); 15 } 16 } 17 }
1 /** 2 * 消费者线程 3 */ 4 public class MyThreadB extends Thread{ 5 private MyService service; 6 7 public MyThreadB(MyService service) { 8 this.service = service; 9 } 10 11 @Override 12 public void run() { 13 for (int i = 0; i < Integer.MAX_VALUE; i++) { 14 service.get(); 15 } 16 } 17 }
1 /** 2 * 交替打印测试类 3 */ 4 public class Run { 5 6 /** 7 * 由于使用的是signalAll() 可能唤醒的是同类,那么就会出现练习执行多次set或者get,连续打印现象 8 */ 9 public static void main(String[] args) { 10 MyService service = new MyService(); 11 12 MyThreadA[] threadA = new MyThreadA[10]; 13 MyThreadB[] threadB = new MyThreadB[10]; 14 15 for (int i = 0; i < 10; i++) { 16 threadA[i] = new MyThreadA(service); 17 threadB[i] = new MyThreadB(service); 18 threadA[i].start(); 19 threadB[i].start(); 20 } 21 } 22 }
运行结果如下: