Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中仅运行线程一分钟_Java_Concurrency - Fatal编程技术网

在java中仅运行线程一分钟

在java中仅运行线程一分钟,java,concurrency,Java,Concurrency,在一段时间内运行线程的最佳实践是什么? 我可以很容易地检查currentTime并在工作一段时间后关闭线程,但我认为这不是正确的方法。这取决于您想要实现的目标,但一般来说,您提到的从一开始测量时间的方法并没有那么错。我会这样编码: private static class MyTimerTask extends TimerTask { private final Thread target; public MyTimerTask(Thread target) { this.tar

在一段时间内运行线程的最佳实践是什么?
我可以很容易地检查currentTime并在工作一段时间后关闭线程,但我认为这不是正确的方法。

这取决于您想要实现的目标,但一般来说,您提到的从一开始测量时间的方法并没有那么错。

我会这样编码:

private static class MyTimerTask extends TimerTask {
    private final Thread target;
    public MyTimerTask(Thread target) { this.target = target; }
    public void run() {
        target.interrupt();
    }
}

public void run() {
    Thread final theThread = Thread.currentThread();
    Timer timer = new Timer();
    try {
         timer.schedule(new MyTimerTask(theThread), 60000});
         while(!theThread.interrupted()) {
             ....
         }
    } finally {
         timer.cancel();
    }
}
。。。这是气垫船描述的,除了使用中断而不是特殊标志。使用中断的好处是,一些I/O调用会被中断解除阻塞,一些库会尊重它。

我很惊讶(也非常失望)没有人提到中断。它已经篡夺了计时器框架(或者至少是
java.util.Timer
类)作为计划任务的“goto”

比如说,

// Start thread
final Thread t = new Thread(new Runnable(){
    @Override
    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            try{
                // do stuff
            }
            catch(InterruptedException e){
                Thread.currentThread().interrupt();
            }
        }
    }
});
t.start();

// Schedule task to terminate thread in 1 minute
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.schedule(new Runnable(){
    @Override
    public void run(){
        t.interrupt();
    }
}, 1, TimeUnit.MINUTES);

差不多吧
public void run(){long start=System.currentTimeMillis();while(System.currentTimeMillis()-start)为正在运行的代码设置一个可变的布尔标志,比如称为
terminate
,加上getter和setter--
setTerminate(boolean terminate)
isTerminate()
,并检查正在运行的线程中该变量的状态,如果为true,则停止该变量。然后使用对象帮助决定何时停止正在运行的线程。@HoverCraftFullOfels+1是一个很好的建议,但您必须同意,这比OP最初的建议要复杂得多:)优点是可以很好地分离导致线程停止的实际情况。但是考虑到问题的确切要求,我不能说简单的方法有任何错误。这需要更多的工作,但是(可能)效率更高。我只想在几个线程中垃圾邮件发送我的mq一分钟。我还从来没有使用过并发包,所以我认为java有一些专门的人员来完成这项任务,比如Scheduler。但是我喜欢@HoverCraftfullOfels解决方案。