Reputation: 79
I a trying to find out, after complete first thread completely than start second thread, after complete second thread than start third thread, Please help me!!
Here is my code:
public class wait {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("First Thread");
createtheard2();
}
public static void createtheard2() {
try {
System.out.println("Second Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
createtheard3();
}
public static void createtheard3() {
try {
System.out.println("Third Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
}
}
After complete first thread, than start second thread, after complete second thread, than start third thread, Please help me!! Thanks!!
Upvotes: 0
Views: 1048
Reputation: 1428
As it was pointed out, using threads in this case does not make sense as you are executing tasks sequentially.
However, it is possible to have a single thread running at a time with SingleThreadExecutor
For example, you
ArrayList
will do the job)ExecutorService.execute()
)Thread.join()
)tasks.remove(currentTask);
ExecutorService.shutdown()
)Alternatively, you could use ExecutorService.invokeAll()
using a single thread executor.
You could even simply run the tasks directly in a loop, invoking start()
, however, I'd really recommend against using concurrency where it is not a necessity.
Upvotes: 0
Reputation: 11298
I think what you need is if task 1 (thread in your terms) success, run task2 else wait for task1. consider the following.
public class Process{
public static void runProcess1() {
boolean done = false;
do {
// make done=true after task1 is done
} while (done);
runProcess2();
}
public static void runProcess2() {
boolean done = false;
do {
// make done=true after task2 is done
} while (done);
runProcess3();
}
public static void main(String[] args) {
runProcess1();
}
}
Upvotes: 0
Reputation: 1594
Implement Runnable
public class ThreadDemo implements Runnable { public void run() { //Do this what you need } }
Use join to wait while thread will be completed.
Thread t1 = new Thread(new ThreadDemo()); // this will call run() function t1.start(); // waits for this thread to die t1.join(); Thread t2 = new Thread(new ThreadDemo()); // this will call run() function t2.start(); // waits for this thread to die t2.join();
From http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
t.join() causes the current thread to pause execution until t's thread terminates.
In your case paused by join method invocation thread will be Main thread.
Upvotes: 2