在java Thread中,我可以使用wait()
和notify()
轻松地在两个线程之间进行通信。
但是假设我有10个线程在运行,比如T1
到T10
,并且我想让线程T2
与线程T7
通信。
我怎么能做到这一点?请举出一些例子以示感谢。
发布于 2015-12-10 19:11:48
线程之间的通信可以通过等待/通知进行,但非常复杂(要正确处理),特别是当涉及两个以上的线程时。
更现代的Java解决方案更适合于BlockingQueue中的线程间通信。
要使用它们,请在创建线程之前创建一个在两个线程之间共享的队列。然后,在创建队列时将队列传递给每个线程。然后它们都持有队列,一个写入队列,另一个读取队列。
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();
}
}
发布于 2015-12-10 19:14:28
下面是一个例子
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);
}
https://stackoverflow.com/questions/34200294
复制相似问题