2014-09-30 2 views
1

JBoss에서 관리하는 스레드가 두 개 있습니다 (시작 방법 없음). 그 중 하나가 루프에 들어가면 다른 하나는 그것을 죽일 수 있어야합니다. 즉, 한 스레드에서 다른 스레드로 메시지 (또는 예외)를 보내려면 어떻게해야합니까? 독립 스레드간에 통신 할 수있는 방법이 있습니까?두 스레드 간 통신 방법

미리 감사드립니다.

종류는 BlockingQueue를 사용하는 가장 좋은 방법 중

+0

실제로 여기, 성취하려는거야? –

+0

... 강제로 다른 스레드를 죽이는 것은 거의 항상 나쁜 생각이기 때문에. –

답변

0

하나 간주한다. 주 스레드에서 대기열을 초기화해야합니다. 블로킹 큐에 쓰는 예제가 있고 스레드의 블로킹 큐에서 읽는 방법을 보여줍니다. 이 예제는 스레드 내에서 블로킹 큐에 대한 읽기/쓰기 작업에 쉽게 적용 할 수 있습니다. 스레드를 종료하려면 스레드를 읽을 때 차단할 수있는 차단 대기열에 감시 값을 쓸 수 있습니다.

주요 드라이버 :

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(); 
      } 
     } 
    } 
}