简体   繁体   English

Java线程..导致线程在设置的时间后终止

[英]Java threads.. cuasing the thread to terminate after a set time

I have written some code that submits a callable to an executor, storing the future in a map against an id. 我写了一些代码,将一个可调用对象提交给执行者,将未来存储在一个ID中。 In the call method I wait for a flag to be set before proceeding. 在调用方法中,我等待设置标志,然后再继续。 Basically I need to wait for an external operation to return to me and say we are done - here is the data and now you can continue... I dont think what I have is correct: 基本上,我需要等待外部操作返回给我,并说我们已完成-这是数据,现在您可以继续...我认为我所拥有的不正确:

public class MyClass implements Callable<Boolean> {

    ---
    ---
    private boolean done = false;

    @override
    public Boolean call() {

        --  wait for flag to be set...
        //continue....
    }

}

--main code-- -主要代码-

//create the above class..

//submit it...

//get the future store in map...

//-- wait for response from external application...

///tie it up with an id

//set the attribute so the callable can continue and complete..

Questions: 问题:

  1. The above will not work as I am returned a Future and not the object. 上面的方法不起作用,因为我返回了Future而不是对象。 I was thinking of maybe creating a new interface which inherits from the callable class - does that make sense? 我在考虑也许要创建一个从可调用类继承的新接口,这有意义吗?

  2. I need the thread to wait and then die if no response is received. 我需要线程等待,如果没有收到响应,则死掉。 Is it possible to set that on a thread at all? 是否可以将其设置在线程上?

You can schedule a task which will cancel the waiting task. 您可以安排任务以取消等待的任务。 When the waiting task finishes it can cancel the scheduled task. 等待任务完成时,它可以取消计划的任务。 (which ever finished first will cancel the other) (先完成的将取消另一个)

This assumes you have a task which is interruptible in the first place. 假设您首先要执行一项可中断的任务。

there is a wait(long timeout) function available.. heres some documentation on it 有一个等待(长超时)功能可用..这里有一些文档

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html

with this wait(long timeout) function, the thread will wait until it gets a notify() (or notifyAll()) OR until the timout expires. 使用此wait(long timeout)函数,线程将等待,直到它获得notify()(或notifyAll())或直到timout过期为止。

any of the following will break the wait(); 以下任何一项都会破坏wait();

  1. notify(); 通知();
  2. notifyAll(); notifyAll();
  3. timout gets reached timout达到

Use the Future#get(long, TimeUnit) . 使用Future#get(long, TimeUnit)

This will wait for some time for an answer, and throw a TimeoutException if there is no return value in the given period. 这将等待一段时间,直到给出的时间TimeoutException内没有返回值时,抛出TimeoutException Then just catch the exception and let the thread finish grafefully. 然后只捕获异常,让线程令人满意地完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM