您的位置:首页 > 编程语言 > Java开发

Java 多线程生产者和消费者代码示例

2013-06-08 14:52 495 查看
共享资源代码:

package com.hycz.producer.consumer;

public class Box {

private int data;
private boolean variable = false; //同步标识符

public synchronized void put(int data){
while(variable){//当同步标识符为true时,所有生产者线程调用的put()方法时都从运行状态变成阻塞状态,不进行生产。
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
variable = true; // 改变标识符
this.data = data;
notifyAll(); // 唤醒所以处于阻塞状态的消费者线程,提醒它们现在产品可以进行消费。
}

public synchronized int get(){
while(!variable){ // 当同步标识符为false时,所有消费者线程调用get()方法时都从运行状态变成阻塞状态,不进行消费。
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
variable = false; // 改变标识符
notifyAll(); // 唤醒所以处于阻塞状态的生产者线程,提醒它们进行产口的生产。
return this.data;
}

}


生产者代码:
package com.hycz.producer.consumer;

public class Producer extends Thread {

private Box box;

public Producer(Box box) {
super();
this.box = box;
}

@Override
public void run() {
for(int i = 0; i<10; i++){
box.put(i);
System.out.println("Producer put = " + i);
try {
Thread.sleep((int)Math.random()*100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}


消费者代码:
package com.hycz.producer.consumer;

public class Consumer extends Thread {

private Box box;

public Consumer(Box box) {
this.box = box;
}

@Override
public void run() {
int value = 0;
for(int i=0; i<10; i++){
value = box.get();
System.out.println("Consumer get = " + value);
}
}

}


测试代码:

package com.hycz.producer.consumer;

public class ProducerConsumerTest {

public static void main(String[] args) {
Box box = new Box();
Thread producer = new Producer(box);
Thread consumer = new Consumer(box);
producer.start();
consumer.start();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: