在java Thread中,我可以使用wait()
和notify()
轻松地在两个线程之间进行通信。
但是假设我有10个线程运行说T1
到T10
,我希望线程T2
与线程T7
进行通信。
我怎么能这样做?一些例子将不胜感激。
答案 0 :(得分:3)
线程之间的通信可以通过wait / notify进行,但非常复杂(为了正确),尤其是当涉及两个以上的线程时。
BlockingQueue更现代的解决方案更适合Java中的线程间通信。
要使用它们,请在创建线程之前创建要在两个线程之间共享的队列。然后在创建时将队列传递给每个线程。然后他们都保持队列,一个写入,另一个读取。
public class TwoThreads {
public static void main(String args[]) throws InterruptedException {
System.out.println("TwoThreads:Test");
new TwoThreads().test();
}
// The end of the list.
private static final Integer End = -1;
static class Producer implements Runnable {
final BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
queue.add(i);
Thread.sleep(1);
}
// Finish the queue.
queue.add(End);
} catch (InterruptedException ex) {
// Just exit.
}
}
}
static class Consumer implements Runnable {
final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
boolean ended = false;
while (!ended) {
try {
Integer i = queue.take();
ended = i == End;
System.out.println(i);
} catch (InterruptedException ex) {
ended = true;
}
}
}
}
public void test() throws InterruptedException {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Thread pt = new Thread(new Producer(queue));
Thread ct = new Thread(new Consumer(queue));
// Start it all going.
pt.start();
ct.start();
// Wait for it to finish.
pt.join();
ct.join();
}
}
答案 1 :(得分:1)
这是示例
public static void main(String[] args) throws Exception {
final Object[] monitors = new Object[10];
final Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
final int num = i;
Thread t = new Thread() {
@Override
public void run() {
final Object mon = monitors[num];
try {
synchronized (mon) {
mon.wait();
}
} catch (InterruptedException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Hello, world from thread " + num);
}
};
Object o = new Object();
threads[i] = t;
monitors[i] = o;
t.start();
}
final Object mon = monitors[5];
synchronized (mon) {
mon.notify();
}
Thread.sleep(10000);
}