package com.ThreadPool; import java.util.LinkedList; /** * 2019-1-8 * @author Administrator * */ public class Lock { public static void main(String[] args) { producerAndConsume producerAndConsume=new producerAndConsume(); new Thread(new Producer(producerAndConsume)).start(); new Thread(new Consume(producerAndConsume)).start(); } } /** * 生产线程 * * @author Administrator * */ class Producer implements Runnable { producerAndConsume producerconsumenull; public Producer(producerAndConsume producerconsume) { this.producerconsumenull = producerconsume; } public void run() { while (true) { producerconsumenull.producer(); try { Thread.sleep(1000); } catch (InterruptedException e) { } } } } /** * 消耗线程 * @author Administrator * */ class Consume implements Runnable { producerAndConsume producerconsumenull; public Consume(producerAndConsume producerconsume) { this.producerconsumenull = producerconsume; } public void run() { while (true) { producerconsumenull.consume(); } } } /** * 模拟生产与消费,生产数量等于消费数量,生产完直接消费,消费完直接生产,循环。。。。。 * * @author Administrator * */ class producerAndConsume implements ProducerAndConsumeInterface { LinkedList<Integer> list = new LinkedList<Integer>(); private static final Object lock = new Object(); int maxSize = 100; public void producer() { synchronized (lock) { while (list.size() >= maxSize) { try { System.err.println("等待消费!不可以生产!"); lock.wait();// 生产线程等待中 } catch (InterruptedException e) { } } System.err.println("正在生产中....."); for (int i = list.size(); i < maxSize; i++) { list.add(i); } try { Thread.sleep(5000);// 等待五秒,模拟生产时间 } catch (InterruptedException e) { } System.err.println("生产完毕!总共"+list.size()+"件商品"); lock.notifyAll();// 释放锁资源,唤醒消费线程 } } public void consume() { synchronized (lock) { while (list.size() < maxSize) { try { System.out.println("等待消费中!!!"); lock.wait(); } catch (InterruptedException e) { } } int size=list.size(); System.out.println("消费中......"); try { Thread.sleep(5000);// 模拟消费时间 } catch (InterruptedException e) { } list.clear(); System.out.println("消费完毕!总共消耗了"+size+"件商品"); lock.notifyAll();// 释放锁资源 } } } interface ProducerAndConsumeInterface { void producer(); void consume(); }