我想制作一个简单的线程程序,以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'毫秒,特别是在加载的系统上。即使它不会持续很长时间,重复睡眠的程序也会累积累积误差。如果您想要保证以特定顺序发生的事情发生,那么您应该使用有保证的同步对象(信号量,队列,倒计数锁存器等) –