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

(转)一段生产者和消费者的简单多线程代码

2008-09-27 10:18 381 查看

一段生产者和消费者的简单多线程代码(转自老紫竹)

package test.thread;
public class Producer extends Thread {
private int number;
private Share shared;
public Producer(Share s, int number) {
shared = s;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
shared.put(i);
System.out.println("生产者" + this.number + "输出的数据为:" + i);
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {}
}
}
public static void main(String args[]) {
Share s = new Share();
Producer p = new Producer(s, 1);
Consumer c = new Consumer(s, 1);
p.start();
c.start();
}
}
class Consumer extends Thread {
private int number;
private Share shared;
public Consumer(Share s, int number) {
shared = s;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = shared.get();
System.out.println("消费者" + this.number + "得到的数据:" + value);
}
}
}
class Share {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) {}
}
contents = value;
available = true;
notifyAll();
}
}
运行结果如下:
生产者1输出的数据为:0
消费者1得到的数据:0
生产者1输出的数据为:1
消费者1得到的数据:1
生产者1输出的数据为:2
消费者1得到的数据:2
消费者1得到的数据:3
生产者1输出的数据为:3
生产者1输出的数据为:4
消费者1得到的数据:4
生产者1输出的数据为:5
消费者1得到的数据:5
生产者1输出的数据为:6
消费者1得到的数据:6
生产者1输出的数据为:7
消费者1得到的数据:7
生产者1输出的数据为:8
消费者1得到的数据:8
生产者1输出的数据为:9
消费者1得到的数据:9
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: