Java 生产者 消费者

z361719298 2009-07-03 11:22:11
谁能给出代码!!!
线程 很不解啊!!
...全文
22 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
361719298 2009-07-03
  • 打赏
  • 举报
回复
dreamhunter_lan 2009-07-03
  • 打赏
  • 举报
回复
可以先去看看操作系统中关于线程同步的内容(进程同步也行),这样会比较好理解为什么需要同步,什么时候需要wait,什么时候去notify或notifyAll,同步方法(也就是synchronized方法)到底是Producer、Consumer中的方法还是应该是被共享的资源中的方法
我给的例子是从Java Tutorial上copy下来的,感觉还不错,上面还有个关于死锁的例子,这份资料不错,LZ可以去下来看看。

import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {
private BlockingQueue<String> drop;

public Producer(BlockingQueue<String> drop) {
this.drop = drop;
}

public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
Random random = new Random();

try {
for (int i = 0; i < importantInfo.length; i++) {
drop.put(importantInfo[i]);
Thread.sleep(random.nextInt(5000));
}
drop.put("DONE");
} catch (InterruptedException e) {}
}
}

import java.util.Random;
import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {
private BlockingQueue<String> drop;

public Consumer(BlockingQueue<String> drop) {
this.drop = drop;
}

public void run() {
Random random = new Random();
try {
for (String message = drop.take(); ! message.equals("DONE");
message = drop.take()) {
System.out.format("MESSAGE RECEIVED: %s%n", message);
Thread.sleep(random.nextInt(5000));
}
} catch (InterruptedException e) {}
}
}

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class ProducerConsumerExample {
public static void main(String[] args) {
BlockingQueue<String> drop = new SynchronousQueue<String> ();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧