[英]Trying to implement a simple java program using Threads
import java.util.Random;
public class ThreadLogic implements Runnable {
private String name;
private int time;
private Random rand = new Random();
public ThreadLogic(String name) {
this.name = name;
this.time = rand.nextInt(1000);
}
public void run() {
try {
System.out.printf("%s is sleeping for %d \n", this.name, this.time);
Thread.sleep(this.time);
System.out.printf("%s is done.\n", this.name);
} catch(Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadLogic("Thread-1"));
Thread t2 = new Thread(new ThreadLogic("Thread-2"));
Thread t3 = new Thread(new ThreadLogic("Thread-3"));
t1.start();
//t1.stop();
t2.start();
t3.start();
t1.stop();
System.out.println("State of Thread-1:"+" "+t1.getState());
System.out.println("State of Thread-2"+" "+t2.getState());
System.out.println("State of Thread-3"+" "+t3.getState());
System.out.println("isalive:"+t1.isAlive());
System.out.println("isalive:"+t2.isAlive());
System.out.println("isalive:"+t3.isAlive());
}
}
從上面的代碼中,我如何在run()
方法中實現這樣的邏輯:如果線程等待超過指定的時間,我想殺死該線程並檢查正在運行的其他兩個線程會發生什么。 當我執行上面的代碼時,它給出了以下輸出。
線程狀態-1:終止
線程狀態-2 RUNNABLE
線程狀態-3 RUNNABLE
的IsAlive:假
的IsAlive:真
的IsAlive:真
線程-2正在睡眠151
線程-3正在睡眠384
線程2完成。
線程3完成。
不應該使用第一個thread.stop()
因為它已被棄用。 (請閱讀此處原因 )
其次考慮使用ExecutorService.submit來執行一個線程; 這將回歸未來 。 在這個future
對象上,您可以在手動等待所需的時間限制后直接調用cancel
, 或者在間隔到期后使用TimeoutException
終止之前調用get
需要等待的時間,可以取消。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.