我想制作一个简单的线程程序,只需使用 sleep() 方法即可按 1、2、3 的顺序启动 3 个线程,然后按 3、2、1 的顺序停止。但是,每次线程都以不同的顺序启动。
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
最佳答案
您的线程以正确的顺序启动,但输出可能是错误的,因为输出消息是同时到达的。您应该将消息传送到主线程中:
public static void main(String[] args) throws InterruptedException {
Thread tr1 = new Thread1();
Thread tr2 = new Thread2();
Thread tr3 = new Thread3();
tr1.start();
System.out.println("Thread 1 started");
tr2.start();
System.out.println("Thread 2 started");
tr3.start();
System.out.println("Thread 3 started");
}
关于java - 使线程在 Java 中以特定顺序启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29697216/