【问题标题】:Java: use timer thread to determin the behavior in the parent threadJava:使用计时器线程来确定父线程中的行为
【发布时间】:2016-11-01 13:25:57
【问题描述】:

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

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

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

【问题讨论】:

  • 您是否尝试过探索 Java 线程:notify() 和 wait() 代替?

标签: java multithreading exception timer


【解决方案1】:

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

如果没有,我会转过头来,在后台线程上执行 executeOperation 位,并包裹在 Future 中。

然后,当前线程可以在 Future 上调用 get,并指定超时时间。

Future<MyResult> futureResult = executor.submit(new Callable<MyResult>(){
   void call(){
       return request.ExecuteOperation();
   }
});
return futureResult.get(2, TimeUnit.MINUTES);

【讨论】:

    【解决方案2】:

    您可以使用CountDownLatchhttps://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html#await(long,%20java.util.concurrent.TimeUnit)。类似的东西:

    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
            }
        }
    }
    

    【讨论】:

    • 此函数等待计数达到 0。我希望在计数时运行执行,如果:计数在 proccecing 发送错误之前结束; else: 一切顺利;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2010-11-18
    相关资源
    最近更新 更多