Reputation: 95
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();
}
}
Upvotes: 0
Views: 613
Reputation: 5048
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();
}
Other way (without threads):
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
Upvotes: 2
Reputation: 1468
Put thread.join ()
after you start the thread. This will wait for the thread to return before the next thread starts.
Upvotes: 0