Java线程通信

use*_*156 1 java multithreading jakarta-ee

在 java Thread 中,我可以使用wait()和轻松地在两个线程之间进行通信notify()

但是假设我有 10 个线程在运行 say T1toT10并且我希望 threadT2与 thread 进行通信T7

我怎么能做到这一点?一些例子将不胜感激。

Old*_*eon 5

线程之间的通信可以通过 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();
    }

}
Run Code Online (Sandbox Code Playgroud)