0

I have a two functions, one is the master and the other is the slave. Via master function I'm trying to learn behaviour of the other function. But I should do whatever calculation is a setted time interval. In this part, how can I set a timer, which is marked a boolean variable if timeout occur, and learn whether timeout occurs ?

func1   -----send message------>   func2  
             start timer
             if timeout occur, do something else
4

2 回答 2

5

您可以func2在另一个线程中执行并让您的原始线程join()具有指定的超时时间。

当然,您需要注意正确的同步。

简单示例(省略InteruptedException处理)

void func1(){
    Thread slave = new Thread(new Runnable(){
         public void run(){
             func2();
         }
    });
    slave.start();
    slave.join(100); // waits 100 milliseconds for slave to complete
    if(!slave.isAlive()){
      //slave completed its task
    }else{
      //slave not done yet, do something else
      somethingElse();
    }
 }
于 2013-05-05T15:21:41.600 回答
2

使用 JDK 中的并发构造。在这种情况下,anExecutorService和 aCountDownLatch是完美匹配的:

    ExecutorService executor = Executors.newCachedThreadPool();

    final CountDownLatch ready = new CountDownLatch(1);
    executor.execute(new Runnable() {
        @Override
        public void run() {
            // do something here
            System.out.println("working ...");
            ready.countDown();
        }
    });


    boolean timeout = !ready.await(1, TimeUnit.MILLISECONDS);
    if (timeout) {
        doSomethingElse();
    }
于 2013-05-05T15:30:44.203 回答