ExecutorService에는 모든 스레드를 중지하고 서비스를 종료하는 shutdownNow 메서드가 있습니다.
편집 : 내가 생각했던대로 스레드를 중지 할 수 없습니다 참조로
나는 shutdownNow의 몇 가지 실험을했고. AFAIK 인터럽트()를 사용하지만 모든 스레드가 인터럽트에 반응하지는 않습니다.
그래서 내가 가지고 올 수있는 최선의 대안 : 당신이 의사 소통을 하나 개의 표시 인스턴스를 공유해야 시작
public static class Indicator{
private boolean isReady = false;
public void ready(){
isReady = true;
}
public boolean isReady(){
return isReady;
}
}
스레드 :
먼저, 지표 클래스를 만들 수 있습니다. 그래서 당신은이 같은 호출 가능을 만들 수 있습니다
public static class Processor implements Callable<Integer> {
private volatile Indicator indicator;
private Integer number;
public Processor(Integer integer, Indicator isReady){
this.number = integer;
this.indicator = isReady;
}
@Override
public Integer call() throws Exception {
System.out.println("Thread started:" + Thread.currentThread().getId());
int counter = 0;
while (!indicator.isReady &&counter < number) {
// Make complicated things
Math.sin(counter);
counter++;
}
if(indicator.isReady){
//another thread finished
//delete resources
System.out.println("Thread interrupted: " + Thread.currentThread().getId() + " " + counter);
return -1;
} else {
System.out.println("Thread finished: " + Thread.currentThread().getId() + " " + counter);
indicator.ready();
return counter;
}
}
}
이 방법을 첫 번째 스레드가 다른 사람을 중지 할 수 있습니다 그들은 himselves 후 청소 준비가되었을 때.
이
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
List<Future<Integer>> clusterFutures = new ArrayList<>();
Indicator indicator = new Indicator();
clusterFutures.add(executorService.submit(new Processor(100, indicator)));
clusterFutures.add(executorService.submit(new Processor(10000, indicator)));
clusterFutures.add(executorService.submit(new Processor(10000000,indicator)));
}
샘플 출력 :
Thread started:11
Thread started:12
Thread finished: 11 100
Thread interrupted: 12 1001
Thread started:13
Thread interrupted: 13 0
(!) 참고가 : 참조 된 클래스는 정적 내부 클래스 그냥에서 실험을 할 쉬웠다 될 필요가 없습니다 다음과 같이
나는이 시도 하나의 파일. 코드의 관점에서
감사합니다. 마침내 다른 스레드를 종료 할 때 실행되는 코드 블록을 갖는 방법이 있습니까? 다른 선물에서 다운로드 한 파일을 정리해야합니다. – user3539951