我想製作一個簡單的線程程序,以1,2,3的順序啓動3個線程,之後按順序停止3,2,1,只需使用sleep()方法。但是,每次線程都以不同的順序啓動。使線程在Java中以特定順序啓動
class Thread1 extends Thread{
public void run(){
System.out.println("Thread 1 running...");
try {
this.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 1 has terminated");
}
}
class Thread2 extends Thread {
public void run(){
System.out.println("Thread 2 running...");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 2 has terminated");
}
}
class Thread3 extends Thread {
public void run(){
System.out.println("Thread 3 running...");
try {
this.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread 3 has terminated");
}
}
public static void main(String[] args) throws InterruptedException {
Thread tr1 = new Thread1();
Thread tr2 = new Thread2();
Thread tr3 = new Thread3();
tr1.start();
tr2.start();
tr3.start();
}
電流輸出:
Thread 1 running...
Thread 3 running...
Thread 2 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated
所需的輸出:
Thread 1 running...
Thread 2 running...
Thread 3 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated
_...線程...以特定的順序...僅使用sleep()._ Thread.sleep()對於演示是可以的,但不要依賴它來同步重要程序中的線程。任何'sleep(n)'調用都可以持續更長的時間,而不是'n'毫秒,特別是在加載的系統上。即使它不會持續很長時間,重複睡眠的程序也會累積累積誤差。如果您想要保證以特定順序發生的事情發生,那麼您應該使用有保證的同步對象(信號量,隊列,倒計數鎖存器等) –