java SE 中是否有线程 block/resume 的标准实现?
Is there standard implementation for thread block/resume in java SE?
我需要阻止一个线程的执行,直到从另一个线程恢复。所以我使用 wait()
方法编写了自己的实现。这似乎有效,但远非简单。
有现成的解决方案吗?最好是 java SE 6?还是我必须使用自己的实现?我没找到。
更新
进一步来说。我需要线程 1 的 work->block->external release->work->end 行为以及从线程 2 释放块的能力。
看看 java.util.conucurrent
中的 类 ...
如果我正确理解你的问题,CountDownLatch
可能是你问题的解决方案。
使用 ExecutorService 并调用 invokeAll 也可能是一种选择。
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
通过这种方式,您还可以指定所有任务都应该完成的超时时间。如果您想拥有一个响应式应用程序,这通常是一个很好的主意。
I need to block execution of a thread until resumed from another thread.
信息不足。您是否需要一个完全由一个线程控制并由另一个线程服从的 on/off 开关?这可能是旋转门的一个很好的应用:Pause thread from another thread(s) and also stop/start it yet from another thread
或者您需要 "one-shot" 行为? (即,"background" 线程每次在 "foreground" 线程允许它执行时做一件事。)这对于 java.util.concurrent.Semaphore
.
来说是一个很好的应用程序
或者,您需要一些其他行为吗?
受其他答案的启发,我找到了两个解决方案:
第一个:
在没有 (0
) 许可的情况下创建 Semaphore
:Semaphore semaphore = new Semaphore(0);
在第一个线程中。并与您的第二个线程分享对它的引用。
在第一个线程中做一些工作,当你想停止执行时调用semaphore.acquire();
。
稍后从第二个线程调用 semaphore.release();
以解除对第一个线程的阻塞。
第二个:
使用初始计数 1
创建 CountDownLatch
:CountDownLatch countDownLatch = new CountDownLatch (1);
再一次,与两个线程共享对它的引用。
如果您希望阻止第一个线程的执行,请调用 countDownLatch.await();
。
第一个线程可以通过在第二个线程中的某处调用 countDownLatch.countDown();
来恢复。
我需要阻止一个线程的执行,直到从另一个线程恢复。所以我使用 wait()
方法编写了自己的实现。这似乎有效,但远非简单。
有现成的解决方案吗?最好是 java SE 6?还是我必须使用自己的实现?我没找到。
更新 进一步来说。我需要线程 1 的 work->block->external release->work->end 行为以及从线程 2 释放块的能力。
看看 java.util.conucurrent
中的 类 ...
如果我正确理解你的问题,CountDownLatch
可能是你问题的解决方案。
使用 ExecutorService 并调用 invokeAll 也可能是一种选择。
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
通过这种方式,您还可以指定所有任务都应该完成的超时时间。如果您想拥有一个响应式应用程序,这通常是一个很好的主意。
I need to block execution of a thread until resumed from another thread.
信息不足。您是否需要一个完全由一个线程控制并由另一个线程服从的 on/off 开关?这可能是旋转门的一个很好的应用:Pause thread from another thread(s) and also stop/start it yet from another thread
或者您需要 "one-shot" 行为? (即,"background" 线程每次在 "foreground" 线程允许它执行时做一件事。)这对于 java.util.concurrent.Semaphore
.
或者,您需要一些其他行为吗?
受其他答案的启发,我找到了两个解决方案:
第一个:
在没有 (0
) 许可的情况下创建 Semaphore
:Semaphore semaphore = new Semaphore(0);
在第一个线程中。并与您的第二个线程分享对它的引用。
在第一个线程中做一些工作,当你想停止执行时调用semaphore.acquire();
。
稍后从第二个线程调用 semaphore.release();
以解除对第一个线程的阻塞。
第二个:
使用初始计数 1
创建 CountDownLatch
:CountDownLatch countDownLatch = new CountDownLatch (1);
再一次,与两个线程共享对它的引用。
如果您希望阻止第一个线程的执行,请调用 countDownLatch.await();
。
第一个线程可以通过在第二个线程中的某处调用 countDownLatch.countDown();
来恢复。