本文共 2392 字,大约阅读时间需要 7 分钟。
sleep()和wait()方法的异同:
同:
不同点:
package com.ran;import java.util.concurrent.locks.ReentrantLock;public class Ran { public static void main(String[] args) { Dianyuan dianyuan=new Dianyuan(); Producer p1 = new Producer(dianyuan); p1.setName("生产者1"); Costumer c1 = new Costumer(dianyuan); c1.setName("消费者1"); p1.start(); c1.start(); }}class Dianyuan{ private int productCount=0; //生产产品 public synchronized void produceProduct() { if(productCount < 20){ productCount++; System.out.println(Thread.currentThread().getName()+":开始生产第"+productCount+"个产品"); notify(); }else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } //消费产品 public synchronized void consumeProduct() { if(productCount > 0){ System.out.println(Thread.currentThread().getName()+":开始消费第"+productCount+"个产品"); productCount--; notify(); }else { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }}class Producer extends Thread{ private Dianyuan dianyuan; public Producer(Dianyuan dianyuan) { this.dianyuan = dianyuan; } @Override public void run() { System.out.println(getName()+"开始生产产品......"); while (true){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } dianyuan.produceProduct(); } }}class Costumer extends Thread{ private Dianyuan dianyuan; public Costumer(Dianyuan dianyuan) { this.dianyuan = dianyuan; } @Override public void run() { System.out.println(getName()+"开始消费产品......"); while (true){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } dianyuan.consumeProduct(); } }}
转载地址:http://okox.baihongyu.com/