【问题标题】:Async return with delay - IllegalMonitorStateException延迟异步返回 - IllegalMonitorStateException
【发布时间】:2018-09-26 06:01:37
【问题描述】:

我正在尝试在新线程中调用方法,该方法将在使用 callable 延迟后返回一些东西。由于 IllegalMonitorStateException 而下降 当我只创建类的实例,调用方法并且该方法将延迟返回对象时,是否可以以这种方式封装线程服务? 提前谢谢你。

// ENTITY
public class Result {
    public String name;
    public int value;

    public Result(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public Result() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Result{" +
                "name='" + name + '\'' +
                ", value=" + value +
                '}';
    }
}

创建带有延迟和返回值的线程

import java.util.concurrent.*;

public class AsyncCallable {

    public Result calculate() throws ExecutionException, InterruptedException {

        int delay = 5000;
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<Result> callable = () -> {
            this.wait(delay);
            return new Result("Name", 4);
        };

        Future<Result> future = executorService.submit(callable);
        executorService.shutdown();
        return future.get();
    }

}

调用方法:

import java.util.concurrent.ExecutionException;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        AsyncCallable asyncCallable = new AsyncCallable();

        System.out.println(asyncCallable.calculate().toString());


    }
}

【问题讨论】:

    标签: java multithreading asynchronous callable


    【解决方案1】:

    因为您的ExecutorService 只使用一个线程,所以只调用Thread#sleep 而不是Object#wait 应该没问题:

    Callable<Result> callable = () -> {
        Thread.sleep(5_000);
        return new Result("Name", 4);
    };
    

    【讨论】:

    • 感谢您的回复,此解决方案有效,但它并没有完全符合我的预期。它不应该暂停整个应用程序(但在我的示例中确实没有关系)
    【解决方案2】:

    好吧,要坚持你的情况,对 wait() 的任何调用都必须包含在同步块中(参见方法 javadoc here)。但是,我认为您应该考虑使用内置工具,例如Scheduled thread pool。使用它,您可以执行以下操作:

    import java.util.concurrent.ScheduledThreadPoolExecutor;
    import java.util.concurrent.Executors;
    
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);
    // Execute a task after 5 seconds
    scheduler.schedule(() -> new Result("Name", 4), 5, TimeUnit.SECONDS);
    

    【讨论】:

    • 好的,所以我被否决了,显然,我的回答对于问题作者来说还不够。是否可以获得有关我的答案有什么问题的更多详细信息?这样我可以尝试改进它。
    • 好吧,我没有足够的代表来投反对票。无论如何,我将您的解决方案与 ScheduledExecutorService 一起使用,它就像一个魅力!我会在获得代表后投票。非常感谢! :-)
    猜你喜欢
    • 2018-06-13
    • 2016-10-29
    • 2016-02-02
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2018-08-01
    相关资源
    最近更新 更多