如何启动两个线程,其中thread1首先执行,当thread1结束时线程2启动,而主方法线程可以继续工作而不锁定另外两个线程?我已经尝试过join(),但它需要从线程中调用,必须等待另一个线程,因为没有办法像thread2.join(thread1)这样做。 如果我在main()内部调用一个连接,我因此有效地停止了主线程的执行,而不仅仅是thread2的执行。当主线程继续执行时,执行两个等待另一个线程的线程
因此,我尝试使用ExecutorService,但同样的问题。
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)
{
//I should execute thread 2 only after thread 1 has finished
executor.execute(new TestThread("2"));
}
//I should arrive here while process 1 and 2 go on with their execution
System.out.println("Hello");
}
}
#EDIT:为什么我需要这样的:
我需要这个,因为从数据库表线程1份的元素到另一个数据库,线程2具有复制它引用从线程1复制的表,一个链接表。 因此,thread2必须仅在thread1完成时才开始填充链接表,否则数据库会给出完整性错误。 现在想象一下,由于复杂的链接表,我有几个不同优先级的线程,你有一个想法。
你为什么需要2个线程,如果他们强制执行了一个又一个? – Tala
我在上面添加了“为什么我需要这个”。希望它很明确 – dendini
不是真的,没有。 –