java中的线程间通信 [英] inter thread communication in java
问题描述
彼此依赖的线程如何用Java进行通信?
How do threads that rely on one another communicate in Java?
例如,我正在构建一个带有线程的Web爬虫,这些线程需要来自其他线程的数据。
For example, I am building a web crawler with threads that need data that comes from other threads.
推荐答案
这取决于沟通的性质。
- 它是双工的(即A与B和B对话是否与A对话)?
- 是完成的数据通信还是通信?
- 依此类推。
- Is it duplex (ie A talks to B and B talks to A)?
- Is it communication of data or communication of completion?
- and so on.
最简单,最可取的线程间通信形式是只是等待其他线程的完成。使用 Future
最容易做到:
The simplest and most advisable form of inter-thread communication is simply to wait for the completion of other threads. That's most easily done by using Future
:
ExecutorService exec = Executors.newFixedThreadPool(50);
final Future f = exec.submit(task1);
exec.submit(new Runnable() {
@Override
public void run() {
f.get();
// do stuff
}
});
第二项任务在第一项任务完成前不会执行。
The second task won't execute until the first completes.
Java 5+有许多并发实用程序来处理这类事情。这可能意味着使用 LinkedBlockingQueue
s, CountDownLatch
或许多其他人。
Java 5+ has many concurrent utilities for dealing with this kind of thing. This could mean using LinkedBlockingQueue
s, CountDownLatch
or many, many others.
深入检查并发性< a href =http://rads.stackoverflow.com/amzn/click/0321349601 =noreferrer> Java Concurrency in Practice 是必读的。
For an in-depth examination of concurrency Java Concurrency in Practice is a must-read.
这篇关于java中的线程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!