Java:使用计时器线程确定父线程中的行为

Java:使用计时器线程确定父线程中的行为,java,multithreading,exception,timer,Java,Multithreading,Exception,Timer,我正在用java编写代码,并从另一个系统发出请求。我希望,如果我在计数(并行)时没有得到响应,我将调用发送错误函数或抛出异常,以便在主线程中捕获 try { StartTimer(); result = request.ExecuteOperation(); sendSuccess(result); } catch (MyExeption ex) { handleExeption(ex!= null? ex.getMessage(): "General Exeption

我正在用java编写代码,并从另一个系统发出请求。我希望,如果我在计数(并行)时没有得到响应,我将调用发送错误函数或抛出异常,以便在主线程中捕获

try {
   StartTimer();
   result = request.ExecuteOperation();
   sendSuccess(result);
} 
catch (MyExeption ex) {
   handleExeption(ex!= null? ex.getMessage(): "General Exeption", ex, systemID)
}

StartTimer()
如何计算2分钟,并检查
ExecuteOperation()
是否返回,以及抛出将在主线程中捕获的MyException是否已过2分钟?

首先,许多阻塞API调用都有一个您可以使用的超时参数

如果没有,我会改变这一点,在后台线程上执行
执行操作
位,并在将来包装

然后,当前线程可以在指定超时的情况下在将来调用
get

Future<MyResult> futureResult = executor.submit(new Callable<MyResult>(){
   void call(){
       return request.ExecuteOperation();
   }
});
return futureResult.get(2, TimeUnit.MINUTES);
Future-futuresult=executor.submit(new Callable()){
无效调用(){
返回请求。ExecuteOperation();
}
});
返回futuresult.get(2,时间单位:分钟);

您可以使用
倒计时锁存器。比如:

public class Test {

    public void executeOperation(CountDownLatch latch ) {
        // runs on separate thread and perform the operation
        latch.countDown();
    }

    public static void main(String[] args) throws Exception {
        Test test = new Test();

        CountDownLatch latch = new CountDownLatch(1);
        test.executeOperation(latch);
        if (!latch.await(2, MINUTES)) {
            // report an error
        }
    }
}

您是否尝试研究Java线程:notify()和wait()?此函数等待直到计数达到0。我希望执行在计数时运行,如果:计数在处理发送错误之前结束;否则:一切正常,重新开始程序;