0

java.util.concurrency受包的启发,我完成了自己的小型并发框架(仅用于学习目的) 。这是关于 Callable/Future 机制的。我下面的代码是完整的,可编译且非常容易理解。

我的问题是,有时我会遇到死锁,第一个线程(main thread)等待来自另一个线程的信号。但是在主线程进入等待状态之前,其他线程已经通知了主线程,所以主线程无法唤醒。

FutureTask.get()应该总是在之前 FutureTask.run()运行,但有时 run() 方法(由 调用new thread)在 get() 方法(由 调用)之前运行main thread。我不知道如何防止这种情况发生。

这是我希望两个线程如何运行的伪代码。

//From main thread:
Executor.submit().get() (in get() the main thread waits for new thread to notify)
         ->submit() calls Executor.execute(FutureTask object)
                                   -> execute() starts new thread
                                                 -> new thread shall notify `main thread`

我无法理解新线程如何比实际启动新线程的主线程更快地启动和运行。

4

1 回答 1

2

condition.await();检查结果是否已经设置之前。

于 2012-09-15T09:45:22.137 回答