标签:开关 print 生产者 cat 使用 通讯 runnable color ==
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Five { public static void main(String[] args) { final Service myService = new Service(); for(int i = 0 ; i < 10 ; i ++){ Thread thread = new Thread(new Runnable() { @Override public void run() { while(true){ myService.push(); } } }); thread.start(); } for(int i = 0 ; i < 10 ; i ++){ Thread thread = new Thread(new Runnable() { @Override public void run() { while(true){ myService.pop(); } } }); thread.start(); } } } class Service{ //创建锁 private ReentrantLock lock = new ReentrantLock(); //创建通讯器 private Condition condition = lock.newCondition(); //创建一个开关 private boolean off = false; public void push(){ try { lock.lock(); if(off == false) condition.wait(); System.out.println("生产!"); off = false; condition.signalAll(); } catch (Exception e) { // TODO: handle exception }finally { lock.unlock(); } } public void pop(){ try { lock.lock(); if(off == true) condition.wait(); System.out.println("消费!"); off = true; condition.signalAll(); } catch (Exception e) { // TODO: handle exception }finally { lock.unlock(); } } }
标签:开关 print 生产者 cat 使用 通讯 runnable color ==
原文地址:https://www.cnblogs.com/monkSand/p/9785738.html