我不明白爲什麼我的簡單程序中的線程總是無法終止。 我認爲它是一個簡單的問題,但我不明白爲什麼。我認爲一個簡單的exec.shutdown();應該關閉我的Threadpool而不用嘗試並捕獲exec.shutdownNow();但大壩不確定。Java:爲什麼線程不會終止
類1:測試(實現一類正在運行的線程池)
public class test {
public static void main(String[] args) throws InterruptedException{
ExecServicrunnen x = new ExecServicrunnen();
x.runningThreads();
Thread.sleep(10000);
x.getThreadtoStop();
}
}
類2:()實現了與MyTask(一個線程池作爲的Runnable)ExecServicerunnen
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ExecServicrunnen {
private volatile boolean solange = true;
public void runningThreads(){
ExecutorService exec = Executors.newFixedThreadPool(5);
while(solange){
exec.execute(new myTask());
}
exec.shutdown();
try{
if(!exec.awaitTermination(60, TimeUnit.SECONDS)){
exec.shutdownNow();
}
} catch (InterruptedException e){
e.printStackTrace();
exec.shutdownNow();
}
}
public void getThreadtoStop(){
solange = false;
}
}
類3: myTask(正在等待一段時間)
public class myTask implements Runnable{
public void run() {
// doSomething
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
該程序始終無法終止吃了。
啊現在它編譯了,我改變了x的方法名稱以獲得更好的讀取,但忘記了更改對象本身的方法名稱。 –
線程問題仍然存在。 –