如何启动两个线程,其中线程1首先执行,当线程1结束时,线程2开始运行,同时主方法线程可以在不锁定其他两个线程的情况下继续工作?
我尝试使用join()但是必须从等待另一个线程的线程中调用它,没有办法像thread2.join(thread1)这样做; 如果我在main()内部调用join,则实际上停止了主线程的执行,而不仅仅是停止了线程2。
因此,我尝试使用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");
}
}
#编辑:为什么我需要这个:
我需要这个是因为Thread1将数据库表中的元素复制到另一个数据库中,Thread2必须复制引用从Thread1复制的表的链接表。 因此,只有当Thread1完成后,Thread2才能开始填充其链接表,否则数据库会给出完整性错误。 现在想象一下,我有几个线程具有不同的优先级,由于复杂的链接表,您就有了一个想法。