按顺序运行线程
问题描述:
假设下面有下面的类,如何强制依次依次执行三个线程? (等待对方终止)
Suppose I have the following class below, how can I force the three threads to be executed in order, one after the other successively? (waiting for each other to be terminated)
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("Thread 1 :First Thread started");
}
public static Runnable delay(){
Runnable r = new Runnable(){
@Override
public void run() { // running state
System.out.println("Thread 2: loading second thread..");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: System loaded");
}
}; // finished state
return r;
}
public static Runnable waiting(){
Runnable r = new Runnable(){
@Override
public void run() { // running state
System.out.println("Thread 3: waiting..");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 3: OK");
}
}; // finished state
return r;
}
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(delay());
Thread thread3 = new Thread(waiting()); // (initial state)
thread1.start();
thread2.start();
thread3.start();
}
}
答
是的,但是为什么要这么做?
Yes there are, but why do you want to do it?
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(delay());
Thread thread3 = new Thread(waiting()); // (initial state)
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
}
其他方式(无线程):
public static void main(String[] args) throws InterruptedException{
new MyRunnable().run();
delay().run();
waiting().run();
}
您的代码可以执行以下操作:
Your code do this:
Main thread thread-1 thread-2 thread-3
V
|
+ . . . . . . > V
+ . . . . . . . | . . . . . . > V
+ . . . . . . . | . . . . . . . | . . . . . . > V
X | | |
X | |
| |
X |
|
X
您要求这样做(这没有意义,因为线程可以并行化任务,并且您不想对其并行化!):
You asked for this (it no make sense because threads can parallelize tasks, and you don't want to parallelize them!):
Main thread thread-1 thread-2 thread-3
V
|
+ . . . . . . > V
| |
|<--------------X
+ . . . . . . . . . . . . . . > V
| |
| |
| |
| |
|<------------------------------X
+ . . . . . . . . . . . . . . . . . . . . . . > V
| |
| |
| |
| |
| |
| |
|<----------------------------------------------X
X