1. 程式人生 > >Java執行緒wait()和notify()的簡單使用

Java執行緒wait()和notify()的簡單使用

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(); }