2010. 6. 29. 16:08
wait 상태의 Thread 를 종료하고 싶을 때.. interrupt 를 사용하자.
뭐.. 스레드를 종료할 때 항상 interrupt 를 사용해서 종료하면 좋다고는 함.
1. SampleThread.java
- interrupt 를 사용해서 thread 를 종료한다.
2. 테스트
뭐.. 스레드를 종료할 때 항상 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();
}
}
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 + " : " );
}
}
}
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 + " : " );
}
}
}
'java > concurrency' 카테고리의 다른 글
[Concurrency] - shutdown hook 사용하기 (0) | 2010.06.29 |
---|---|
[Concurrency] - Future 를 이용한 작업종료 (0) | 2010.06.29 |
[Concurrency] - ExecutorService 를 이용한 동작주기 예제 (0) | 2010.06.29 |
[Concurrency] - Executor 를 사용한 thread pool 샘플 (0) | 2010.06.29 |
[Concurrency] - BlockingQueue 과 producer-consumer 패턴 활용법 (0) | 2010.06.29 |