彼此依赖的线程如何在Java中进行通信?
例如,我正在构建一个带有线程的Web爬虫,这些线程需要来自其他线程的数据.
以下是Inter线程通信的示例:
public class Main { public static void main(String[] args) { Chat m = new Chat(); new T1(m); new T2(m); } } class Chat { boolean flag = false; public synchronized void FromSam(String msg) { if (flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = true; notify(); } public synchronized void FromJam(String msg) { if (!flag) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(msg); flag = false; notify(); } } class T1 implements Runnable { Chat m; String[] s1 = { "Hello Jam", "How are you ?", "I am also doing fine!" }; public T1(Chat m1) { this.m = m1; new Thread(this, "Sam").start(); } public void run() { for (int i = 0; i < s1.length; i++) { m.FromSam(s1[i]); } } } class T2 implements Runnable { Chat m; String[] s2 = { "HI Sam", "I am good,And U ?", "ha haa" }; public T2(Chat m2) { this.m = m2; new Thread(this, "Jam").start(); } public void run() { for (int i = 0; i < s2.length; i++) { m.FromJam(s2[i]); } } }
这取决于沟通的性质.
它是双工的(即A与B和B会谈到A)吗?
是完成数据的沟通还是沟通?
等等.
最简单和最可取的线程间通信形式只是等待其他线程的完成.这通过使用最容易完成Future
:
ExecutorService exec = Executors.newFixedThreadPool(50); final Future f = exec.submit(task1); exec.submit(new Runnable() { @Override public void run() { f.get(); // do stuff } });
第二个任务在第一个任务完成之前不会执行.
Java 5+有许多并发实用程序来处理这类事情.这可能意味着使用LinkedBlockingQueue
s CountDownLatch
或许多其他.
要深入研究并发性Java Concurrency in Practice是必读的.