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 condition.await(); 18 } 19 System.out.println("☆"); 20 hasValue = true; 21 condition.signal(); 22 } catch (InterruptedException e) { 23 e.printStackTrace(); 24 }finally { 25 lock.unlock(); 26 } 27 } 28 29 public void get() { 30 try { 31 lock.lock(); 32 while(!hasValue) { 33 condition.await(); 34 } 35 System.out.println("★"); 36 hasValue = false; 37 condition.signal(); 38 } catch (InterruptedException e) { 39 e.printStackTrace(); 40 }finally { 41 lock.unlock(); 42 } 43 } 44 }
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 public static void main(String[] args) { 7 MyService service = new MyService(); 8 9 MyThreadA a = new MyThreadA(service); 10 a.start(); 11 MyThreadB b = new MyThreadB(service); 12 b.start(); 13 } 14 }
运行结果如下: