2014-09-30 128 views
1

我有2個線程由JBoss管理(沒有啓動方法)。我需要的是,如果他們中的一個進入循環,那麼另一個必須能夠殺死它。換句話說,我怎樣才能從一個線程向另一個線程發送消息(或例外)?有獨立的線程之間進行通信的方法嗎?如何在兩個線程之間進行通信

非常感謝您提前!

親切的問候

+0

什麼是你真正要完成的,在這裏? – 2014-09-30 18:53:22

+0

...因爲強行殺死另一個線程幾乎總是一個壞主意。 – 2014-09-30 18:55:01

回答

0

一個使用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(); 
      } 
     } 
    } 
} 
相關問題