How can I start two threads where thread1 is executed first, thread2 is started when thread1 ends, when the main method thread can continue its work without blocking on the other two?
I tried join (), however it needs to be called from a thread that should wait for another, there is no way to do something like thread2.join (thread1); If I call for union inside main (), I therefore effectively stop the execution of the main thread, not just thread2.
So I tried with ExecutorService, but again the problem.
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Test { public static void main(String args[]) throws InterruptedException { System.out.println(Thread.currentThread().getName() + " is Started"); class TestThread extends Thread { String name; public TestThread(String name) { this.name = name; } @Override public void run() { try { System.out.println(this + " is Started"); Thread.sleep(2000); System.out.println(this + " is Completed"); } catch (InterruptedException ex) { ex.printStackTrace(); } } @Override public String toString() { return "Thread " + name; } } ExecutorService executor = Executors.newCachedThreadPool(); executor.execute(new TestThread("1")); boolean finished = executor.awaitTermination(1, TimeUnit.HOURS); if(finished) {
#EDIT: why do I need this:
I need this because Thread1 copies elements from the database table to another database, thread2 must copy the link table that refers to the table copied from thread1. Consequently, thread2 should start filling in its bind table only when thread1 has finished, otherwise the whole error is set by the database. Now imagine that I have several threads with different priorities due to complex binding tables, and you have an idea.
source share