[英]Java-How to search an array using a thread for each row and stop all running threads if found?
[英]How to stop each thread at a time in multiple threads in Java?
我需要做的是創建多個線程(例如,示例代碼中的3個線程),並且每個線程都在執行自己的計算。 每個線程完成其計算后,應停止相應的線程。
我從如何停止Java中的線程獲得了代碼? 示例 ,它適用於一個線程。
但是,如果我為多個線程修改此代碼,則每個線程不會停止並保持運行。 這意味着盡管線程完成了doSomeComputation(),但它還是從頭開始重新計算,而不是停止它。
我一直在使用Google搜索和搜索該網站,並嘗試了該方法(使用interrupt,Thread.stop()等)。 但是找不到我想要的方法。 每當在每個線程中完成doSomeComputation()時如何停止每個線程?
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.currentThread;
public class ThreadStopDemo {
public static void main(String args[]) throws InterruptedException {
ThreadStopDemo tsd = new ThreadStopDemo();
tsd.test2(); // NOT stop
// tsd.test1(); // stop
}
// this works well.
void test1() throws InterruptedException {
Server myServer = new Server();
Thread t1 = new Thread(myServer, "T1");
t1.start();
System.out.println(currentThread().getName() + " is stopping Server thread");
myServer.stopThread();
TimeUnit.MILLISECONDS.sleep(200);
System.out.println(currentThread().getName() + " is finished now");
}
// this doesn't stop and keeps running.
void test2() throws InterruptedException {
Server[] pool = new Server[3];
for(int i = 0; i < pool.length; i++) {
pool[i] = new Server();
pool[i].start();
}
for(int i = 0; i < pool.length; i++) {
System.out.println(currentThread().getName() + " is stopping Server thread");
pool[i].stopThread();
TimeUnit.MILLISECONDS.sleep(200);
System.out.println(currentThread().getName() + " is finished now\n");
}
}
}
class Server extends Thread {
private volatile boolean exit = false;
public void run() {
while (!exit) {
System.out.println(currentThread().getName() + " Server is running.....");
doSomeComputation();
}
System.out.println(currentThread().getName() + " Server is stopped....");
}
public void stopThread() {
exit = true;
}
void doSomeComputation() {
...
}
}
等待多個線程的最佳方法是使用ExecutorService.submit() ,然后調用Future.get()以等待作業完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.