2014-09-30 2 views
1

У меня есть 2 потока, которыми управляет JBoss (без метода запуска). Мне нужно, чтобы, если один из них входит в цикл, другой должен уметь его убить. Другими словами, как я могу отправить сообщение (или исключение) из одного потока в другой? Есть ли способ общения между независимыми потоками?Как общаться между двумя потоками

спасибо, что заблаговременно!

Сердечные приветы

+0

Что вы на самом деле пытаетесь достичь здесь? –

+0

... потому что насильственное убийство другой нити почти всегда является плохим идеей. –

ответ

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(); 
      } 
     } 
    } 
} 
Смежные вопросы