62,620
社区成员
发帖
与我相关
我的任务
分享
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();
}
这是我的一段与服务器端异步通信的代码,底层通信是异步的,但是为了给上层应用提供同步的方式调用,特意加了这样的两个方法,思路应该是和你这个需求有相似的地方,可以供你参考。
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) {
thread.interrupt();
System.out.println("Timeout");
if (thread.isInterrupted() && thread.isAlive()) {
System.out.println("Force stop.");
thread.stop();
}
}
}
}
}
class Runnable1 implements Runnable {
@Override
public void run() {
System.out.println("Thread1 start.");
System.out.println("Thread1 end.");
}
}
class Runnable2 implements Runnable {
@Override
public void run() {
System.out.println("Thread2 start.");
/* 耗时操作,但可以通过条件终止。 */
Thread current = Thread.currentThread();
for (int i = 1; i < 100000000; i++) {
if (current.isInterrupted()) {
Thread.interrupted();
break;
}
i = i / i;
}
System.out.println("Thread2 end.");
}
}
class Runnable3 implements Runnable {
@Override
public void run() {
System.out.println("Thread3 start.");
/* 无法正常终止的耗时操作,只能Thread.stop()非正常终止。 */
for (int i = 1; i < 100000000; i++) {
i = i / i;
}
System.out.println("Thread3 end.");
}
}
