(转)一段生产者和消费者的简单多线程代码
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
相关文章推荐
- 多线程程序一段问题代码分析(生产者消费者)
- 面试题:用 wait-notify 写一段代码来解决生产者-消费者问题
- Java 多线程生产者和消费者代码示例
- java代码实现多线程消费者生产者问题。
- 生产者消费者问题(附代码)& 多线程 线程池
- 描述消费者和生产者模式的代码(有些公司面试的时候会让你直接写一段代码)
- Java 多线程 生产者与消费者问题测试代码
- python 多线程生产者消费者代码
- 多线程-生产者消费者问题代码2并解决线程安全问题
- 多线程_生产者消费者问题代码1
- 多线程--生产者消费者--简单例子
- 多线程--生产者消费者--简单例子
- 用多线程实现“生产者-消费者问题”(代码+实验报告)
- java多线程之生产者与消费者问题的简单模拟
- 多线程_生产者消费者题代码2并解决线程安全问题
- 多线程_生产者消费者之等待唤醒机制代码优化
- 用 wait-notify 写一段代码来解决生产者-消费者问题?
- 多线程间的同步-经典的生产者与消费者代码
- 多生产者多消费者简单代码示例
- 今天在学习线程的时候接触到消费者和生产者模式,写了简单的代码