我有两个线程,“主”线程,它启动一个次要线程来运行一个小进程。
“主”线程必须等待辅助线程数秒钟才能完成进程,在此之后,“主”线程必须再次启动,不管二级线程的进程发生了什么。
如果辅助进程提前结束,则“主”线程必须重新开始工作。
如何从另一个线程启动线程,等待执行的结束,然后重新启动线程?
这里有一个代码,但是ExampleRun类必须等待,例如,10秒,然后重新启动,不管MyProcess发生了什么
public class ExampleRun {
public static void main(String[] args) {
MyProcess t = new MyProcess();
t.start();
synchronized (t) {
try {
t.wait();
} catch (InterruptedException e) {
System.out.println("Error");
}
}
}}
public class MyProcess extends Thread {
public void run() {
System.out.println("start");
synchronized (this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println("I sleep");
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag = true;
System.out.println("Wake up");
notify();
}
}
}发布于 2014-09-17 21:33:38
实现您想要的目标的最简单方法是使用Thread.join(timeout)。
另外,不对Thread对象使用synchronized、wait或notify。这将干扰Thread.join实现。有关细节,请参阅文档。
以下是您的主程序的样子:
public static void main(String[] args) {
MyProcess t = new MyProcess();
t.start();
try {
t.join(10000L);
} catch (InterruptedException ie) {
System.out.println("interrupted");
}
System.out.println("Main thread resumes");
}注意,当主线程在join()调用之后恢复时,它无法判断子线程是否完成或调用是否超时。要测试这一点,请调用t.isAlive()。
当然,您的子线程可以做任何事情,但重要的是不要在其本身上使用synchronized、wait或notify。例如,下面是一个避免使用这些调用的重写:
class MyProcess extends Thread {
public void run() {
System.out.println("MyProcess starts");
for (int i = 0; i < 5; i++) {
try {
System.out.println("MyProcess sleeps");
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("MyProcess finishes");
}
}发布于 2014-09-17 17:45:31
您可以使用一个简单的锁方法来完成这个任务:
public static void main (String[] args)
{
// create new lock object
Object lock = new Object();
// create and start thread
Thread t = new Thread(() ->
{
// try to sleep 1 sec
try { Thread.sleep(1000); }
catch (InterruptedException e) { /* do something */ }
// notify main thread
synchronized (lock) { lock.notifyAll(); }
};
t.start();
// wait for second thread to finish
synchronized (lock)
{
while (t.isAlive())
lock.wait();
}
// second thread finished
System.out.println("second thread finished :)");
}发布于 2014-09-17 17:46:08
您可以在您想要等待的Thread上调用Thread,根据Javadoc,
等待这个线程死掉。
或者,您可以使用Future,只需从其‘Javadoc’调用get(),
必要时等待计算完成,然后检索其结果。
https://stackoverflow.com/questions/25896989
复制相似问题