【发布时间】:2013-07-04 14:15:20
【问题描述】:
如何启动两个线程,其中 thread1 首先执行,thread2 在 thread1 结束时启动,而 main 方法线程可以继续其工作而不锁定其他两个线程?
我已经尝试过 join() 但是它需要从必须等待另一个线程的线程中调用,没有办法做像 thread2.join(thread1); 这样的事情 如果我调用 main() 内部的连接,我将有效地停止主线程的执行,而不仅仅是线程 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");
}
}
#EDIT:为什么我需要这个:
我需要这个,因为 Thread1 将元素从数据库表复制到另一个数据库,thread2 必须复制一个链接表,该链接表引用从 thread1 复制的表。 因此,只有在 thread1 完成后,thread2 才必须开始填充其链接表,否则数据库会给出完整性错误。 现在想象一下,由于复杂的链接表,我有几个具有不同优先级的线程,你有一个想法。
【问题讨论】:
-
如果强制一个接一个地执行,为什么还需要 2 个线程?
-
我在上面添加了“为什么我需要这个”.. 希望清楚
-
我想我现在说得更清楚了 :)
标签: java multithreading executorservice