wait 상태의 Thread 를 종료하고 싶을 때.. interrupt 를 사용하자.
뭐.. 스레드를 종료할 때 항상 interrupt 를 사용해서 종료하면 좋다고는 함.

1. SampleThread.java
- interrupt 를 사용해서 thread 를 종료한다.
package study.interrupt;

import java.util.concurrent.BlockingQueue;

public class SampleThread extends Thread {

 private final BlockingQueue<String> queue;
 
 SampleThread(BlockingQueue<String> queue) {
  this.queue = queue;
 }
 
 @Override
 public void run() {
  try {
  
   int index = 0;
  
   while(!Thread.currentThread().isInterrupted()) {
    queue.put("" + index);
    System.out.print(index + " : ");
    index ++;
   }
  } catch(InterruptedException e) {
   System.out.println();
  }
 }
 
 public void cancel() {
  interrupt();
 }

}

2. 테스트
package study.interrupt;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Launcher {

 public static void main(String[] args) {
  BlockingQueue<String> queue = new ArrayBlockingQueue(10);
 
  SampleThread t = new SampleThread(queue);
  t.start();
 
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  t.cancel();

  for(String str : queue) {
   System.out.print(str + " : " );
  }

 }
}

Posted by 짱가쟁이