首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

线程通讯(同步唤醒机制)-生产者与消费者

2012-08-24 
线程通信(同步唤醒机制)-生产者与消费者package com.companynamepublic class Test {public static void

线程通信(同步唤醒机制)-生产者与消费者

package com.companyname;public class Test {public static void main(String[] args) {Resource res=new Resource();Thread t1=new Thread(new Product(res));Thread t2=new Thread(new Product(res));Thread t3=new Thread(new Consumer(res));Thread t4=new Thread(new Consumer(res));t1.start();t2.start();t3.start();t4.start();}}class Resource {private int num = 0;private boolean flag=true;public synchronized void produce() {while (true) {if (flag) {System.out.println(Thread.currentThread().getName()+"生产......."+(++num));flag=false;}else{this.notifyAll();    //唤醒对象池上所有冻结的线程try {this.wait();    //当前线程等待} catch (InterruptedException e) {e.printStackTrace();}}}}public synchronized void consume() {while (true) {if(!flag){System.out.println(Thread.currentThread().getName()+"消费"+num);flag=true;}else{this.notifyAll();try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}}}}class Product implements Runnable {private Resource res;public Product(Resource res) {this.res = res;}public void run() {res.produce(); // 生产}}class Consumer implements Runnable {private Resource res;public Consumer(Resource res) {this.res = res;}public void run() {res.consume(); // 消费}}

?

热点排行