文档详情

JavaSE_23_多线程(三)讲解.ppt

发布:2017-03-21约7.58千字共27页下载文档
文本预览下载声明
场景类TestProduct //生产者消费者问题 public class TestProduct { public static void main(String[] args) { Clerk clerk = new Clerk(0); //生产者线程 Thread producerThread = new Thread(new Producer(clerk)); //消费者线程 Thread consumerThread = new Thread(new Consumer(clerk)); producerThread.start(); consumerThread.start(); } } 店员类Clerk(1) public class Clerk { public int product;//现存的商品数量0-20 public Clerk(int product) { this.product = product; } //从生产者处获取商品(进货) public synchronized void addProduct(){ if(this.product=20){ //货满,暂停进货 System.out.println(货满,暂停进货); try {wait();} catch (InterruptedException e) { e.printStackTrace(); }//.....被唤醒后的后续代码 }else{//可以进货 this.product ++; System.out.println(从生产者处获得了第+this.product +个商品); notify();//随机唤醒一个等待执行某个同步方法的对象 } }.....待续 店员类Clerk(2) //向消费者销售商品(卖货) public synchronized void sellProduct(){ if(this.product=0){ System.out.println(售罄,估清,等待生产者提供商品); try {wait();} catch (InterruptedException e) { e.printStackTrace(); }//.....被唤醒后的后续代码 }else{ System.out.println(向消费者销售了第+(this.product) +个商品); this.product --; notify();//唤醒等待在this对象上的线程 } } } 消费者类Comsumer public class Consumer implements Runnable{ private Clerk clerk; public Consumer(Clerk clerk) { super(); this.clerk = clerk; } public void run() { while(true){ clerk.sellProduct();//调用一个Clerk类中的同步方法 try { Thread.sleep((int)(Math.random()*2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } 生产者类Producer public class Producer implements Runnable{ private Clerk clerk; public Producer(Clerk clerk) { super(); this.clerk = clerk; } public void run() { while(true){ clerk.addProduct();//调用一个Clerk类中的同步方法 try { Thread.sleep((int)(Math.random()*1000)); } catch (InterruptedException e) { e.printStackTrace(); } } } } 练习 Wife线程类,负责花钱1万的随机整数倍,每次不超过10万,如果余额不够但不为0,则有多少就花多少,没钱就wait; Husband线程类,负责赚钱,2万的随机整数倍,每次不超过10万;如果余额超过10万(含),则wait;如果余额加上新赚的钱超过10万,则保留(例如余额5万,新赚6万,则新余额11万) Acc
显示全部
相似文档