本文介绍了按顺序运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设下面有下面的类,如何强制依次依次执行三个线程? (等待对方终止)
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
这篇关于按顺序运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!