多线程(三)计算机软件及应用it计算机专业资料PPT课件.pptVIP

  • 22
  • 0
  • 约7.58千字
  • 约 27页
  • 2018-06-20 发布于贵州
  • 举报

多线程(三)计算机软件及应用it计算机专业资料PPT课件.ppt

多线程(三)计算机软件及应用it计算机专业资料PPT课件

场景类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

文档评论(0)

1亿VIP精品文档

相关文档