现在要实现三个线程,线程1管理线程2和3,线程1管理要求:死循环查看线程2和3是否僵死(超过一定时间算僵死,我不知道怎么判断这时间)。线程2和3并发执行,。现在我想知道如何实现线程1管理线程2和3,要求就是,如果线程2或3,超过一定时间还没执行完毕,就重新执行一次,如果三次都僵死,就把这线程杀掉,再启动一个这样的线程,请问该如何实现。谢谢大家了。
------解决方案--------------------
public synchronized Response sendRequest(Request request, long timeout) {
try {
long start = System.currentTimeMillis();
send(request);
this.received = false;
while (!this.received) {
long curr = System.currentTimeMillis();
if (curr - start > timeout) {
return new Response("与服务器通信超时");
}
this.wait(100L);
}
return this.res;
} catch (Exception e) {
log.error(e.getMessage(), e);
return new Response(e.getMessage());
}
}
public synchronized void receive(Response response) {
this.res = response;
this.received = true;
this.notify();
}
这是我的一段与服务器端异步通信的代码,底层通信是异步的,但是为了给上层应用提供同步的方式调用,特意加了这样的两个方法,思路应该是和你这个需求有相似的地方,可以供你参考。
------解决方案--------------------
关系都理清楚了。剩下的就是基本的线程逻辑操作了。
1是守护线程,2,3是worker。用CountDownLatch
给你个参考:
http://www.iteye.com/topic/1002652
------解决方案--------------------
java.util.concurrent.ExecutorService可以吧?
------解决方案--------------------
问题是如何让同一线程重新执行?
------解决方案--------------------
我记得一个线程只能执行一次,所以我用Runnable代替了Thread。而且通过其他线程调用stop()终止自己是不推荐的,可以在自己线程中通过线程的中断状态来终止自己。新手,献丑了。

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class TestThrad {
public static void main(String[] args) {
new Thread1(1000, new Runnable1(), new Runnable2(), new Runnable3());
}
}
class Thread1 extends Thread {
Runnable[] runnables;
long time = 0;
public Thread1(long time, Runnable... runnables) {
this.runnables = runnables;
this.time = time;
// start();
run();
}
@Override
public void run() {
for (final Runnable runnable : runnables) {
new Thread() {
@Override
public void run() {
doRunnable(runnable);
}
}.start();
}
}
void doRunnable(Runnable runnable) {
Thread thread;
FutureTask<Boolean> task;
for (int i = 0; i < 3; i++) {
task = new FutureTask<>(runnable, true);
thread = new Thread(task);
thread.start();
try {
if (task.get(time, TimeUnit.MILLISECONDS))
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {