【问题标题】:How to communicate between two threads两个线程之间如何通信
【发布时间】:2014-09-30 18:46:53
【问题描述】:

我有 2 个由 JBoss 管理的线程(没有启动方法)。我需要如果其中一个进入循环,那么另一个必须能够杀死它。换句话说,我如何从一个线程向另一个线程发送消息(或异常)?有没有办法在独立线程之间进行通信?

非常感谢您!

亲切的问候

【问题讨论】:

  • 你到底想完成什么,在这里?
  • ...因为强行杀死另一个线程几乎总是一个坏主意。

标签: java multithreading spring monitoring


【解决方案1】:

使用BlockingQueue 的最佳方式之一。您必须在主线程中初始化队列。我在下面有一个示例,它写入阻塞队列并显示如何从线程中的阻塞队列中读取。这个例子可以很容易地适应从你的线程中读/写阻塞队列。如果你想关闭你的线程,你可以将一个标记值写入阻塞队列,当你的线程被读取时,它可能会关闭。

主要驱动:

public static void main(String[] args) {

    // A blocking queue used to pass strings to threads
    BlockingQueue<Entry<String> sharedQueue = new LinkedBlockingQueue< String>();

    // The number of cores available on the running machine
    // Note: if Hyper Threading is enabled this will be double the number of
    // physical cores
    int numCores = Runtime.getRuntime().availableProcessors();

    // Create a thread pool of size equal to numCores
    ExecutorService threadPool = Executors.newFixedThreadPool(numCores);

    // Initialize all of the Tasks and add them to the thread pool
    for (int i = 0; i < numCores; i++) {
        Runnable task = new WellFormedStringRunnable(sharedQueue);
        threadPool.execute(task);
    }

    // Do not allow any more tasks to be added and wait for all tasks to be
    // completed before shutting down the executor
    threadPool.shutdown();

    // Read form STDIN and add each line to the shared queue
    try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

        // The current line
        String input;

        // Continue processing until a null character has been reached
        while ((input = br.readLine()) != null) {

            // Add the tuple (line number, string) to the shared queue
            try {
                sharedQueue.put(input);
            } catch (InterruptedException e) {
                System.err.println("Error accessing shared queue: "
                        + e.getMessage());
                threadPool.shutdownNow();
                System.exit(1);
            }
        }

    } catch (IOException e) {
        System.err.println("Error reading from STDIN: " + e.getMessage());
        System.exit(1);
    }


    // Allow all threads to complete
    try {
        threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {

        // If the shared queue throws an exception, display the error and
        // shutdown all running tasks
        System.err.println("Error while waiting for threads to terminate: "
                + e.getMessage());
        threadPool.shutdownNow();
        System.exit(1);
    }

}

线程代码:

public class RunnableThread implements Runnable {

    /** A blocking queue used to retrieve strings */
    private final BlockingQueue<String> sharedQueue;

    public RunnableThread(BlockingQueue<String> sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {

        // Used to hold a value from the shared queue
        String currValue = null;

        // Continue to process strings while the thread is not interrupted and
        while (!Thread.currentThread().isInterrupted()) {
            try {
                // Get a string from the shared queue
                currValue = this.sharedQueue.take();

                // Process Strings
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多