import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Four { public static void main(String[] args) { final Service1 myService = new Service1(); 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 Service1{ //創建鎖 private ReentrantLock lock1 = new ReentrantLock(); private ReentrantLock lock2 = new ReentrantLock(); //創建通訊器 private Condition condition = lock1.newCondition(); //創建一個開關 private boolean off = false; public void push(){ try { lock1.lock(); if(off == false) condition.wait(); System.out.println("生產!"); off = false; //讓線程睡一會,保證B線程能夠被鎖住 Thread.sleep(3000); this.pop(); condition.signalAll(); } catch (Exception e) { // TODO: handle exception }finally { lock1.unlock(); } } public void pop(){ try { lock2.lock(); if(off == true) condition.wait(); System.out.println("消費!"); off = true; Thread.sleep(3000); this.push(); condition.signalAll(); } catch (Exception e) { // TODO: handle exception }finally { lock2.unlock(); } } }