在Java中:如何让线程监视另一个线程? [英] In Java: how can I make thread watch over another thread?

查看:155
本文介绍了在Java中:如何让线程监视另一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,问题很简单。我是初学者。

Sorry if the question is quite simple. I am a beginner.

我必须创建线程来计算某些东西,而第一个线程工作,另一个必须测量第一个线程是否在指定时间内计算函数。如果没有,它必须抛出异常。否则它会返回答案。

I have to create thread that calulates something, while the first thread works the other one have to measure if the first thread calculate the function in specified time. If not, it has to throw exception. Else it returns the answer.

推荐答案

我将采用java.util.concurrent组件 - 简单示例

I'd take the java.util.concurrent components - simple example

public void myMethod() {
    // select some executor strategy
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future f = executor.submit(new Runnable() {
        @Override
        public void run() {
            heresTheMethodToBeExecuted();
        }
    });
    try {
        f.get(1000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // do something clever
    } catch (ExecutionException e) {
        // do something clever
    } catch (TimeoutException e) {
        // do something clever
    }
}

这篇关于在Java中:如何让线程监视另一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆