标签:
import java.util.ArrayList; import java.util.List; public class ProduceAndConsume { public static final Object signal = new Object(); public static List<String> list = new ArrayList<String>(); public static void main(String args[]) { Thread produce = new Thread(new Produce()); Thread consume = new Thread(new Consume()); produce.start(); consume.start(); } } class Produce implements Runnable{ @Override public void run() { int sequence = 0; while(true) { synchronized(ProduceAndConsume.signal){ for (int i = 0; i < 3; i++) { ProduceAndConsume.list.add(sequence + "commodity"); } sequence++; try { ProduceAndConsume.signal.notify(); ProduceAndConsume.signal.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } class Consume implements Runnable{ @Override public void run() { int count = 0; while(count < 5) { synchronized(ProduceAndConsume.signal) { try { ProduceAndConsume.signal.wait(); } catch (InterruptedException e) { e.printStackTrace(); } if(ProduceAndConsume.list.size() > 0) { for (String str : ProduceAndConsume.list) { System.out.println(str); } ProduceAndConsume.list.clear(); count++; ProduceAndConsume.signal.notify(); } } } } }
注意
1.消费和生产一定要用同一把锁ProduceAndConsume.signal
2.ProduceAndConsume.signal.wait()的作用是当前线程暂停,释放锁signal,转到等待队列中,等待signal这个信号量(signal也是锁)的通知。等到signal的通知之后(而不能是其他信号量的通知),这个线程才有机会转到就绪队列中,去竞争执行的机会。
3.ProduceAndConsume.signal.notify()的作用是通知等待在signal这个信号量的单个线程从等待队列中进入就绪队列,准备竞争执行的机会。但调用ProduceAndConsume.signal.notify()方法的线程并不会马上释放锁,而是把代码执行完后再释放锁,因为notify只是通知其他等待在这个信号量的线程进入就绪队列,准备竞争锁。
标签:
原文地址:http://my.oschina.net/u/1583086/blog/505953