一旦其中的线程完成,重新启动线程
Restart thread once the threads inside it finished
我有线程 x
,我是这样开始的:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(() -> {
在 x
我有一个 CyclicBarrier
和另外 10 个线程:
final CyclicBarrier _threadGate = new CyclicBarrier(10);
ArrayList<Thread> _threadList = new ArrayList<>();
然后我将线程添加到列表中
for (int i = 0; i < 10; i++) {
_threadList.add(new Thread() {
@Override
public void run() {
_threadGate.await();
//long processing code
所以在线程准备好后我启动它们,它们同时启动很重要(好吧几乎,循环需要时间,即使它是 0.01 毫秒):
for (int i = 0; i < _threadList.size(); i++) {
_threadList.get(i).start();
}
现在,主线程x
的结尾是这样的:
}, 0, repeatTimer, TimeUnit.SECONDS);
如果 repeatTimer
是 300
这意味着它将在 5 分钟后再次启动 10 个线程。
10 个线程完成的时间未知,但不到 5 分钟。肯定在 2 到 4 分钟之间。
我想达到的目标
10 个线程完成后,重新启动 X,但延迟 5 秒。
为此,我一直在考虑将 repeatTimer
值设置为 10 个线程经过的时间 + 5 秒(我不知道该怎么做,我不知道最后一个线程何时完成其任务),但这是正确的?或者有其他方法吗?
我不认为这里有 SchedulingExecutorService
的必要性。您可以等待所有线程使用 CountDownLatch 完成它们的工作。
这是一个简单的例子:
while (!stopped) {
CountDownLatch latch = new CountDownLatch(N);
// create and start your threads
latch.await(); // this method blocks until each Thread calls countDown()
// wait here 5 seconds if you want
}
在每个线程的最后一个动作中递减锁存器:
public void run() {
_threadGate.await();
// thread actions
latch.countDown();
}
我有线程 x
,我是这样开始的:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(() -> {
在 x
我有一个 CyclicBarrier
和另外 10 个线程:
final CyclicBarrier _threadGate = new CyclicBarrier(10);
ArrayList<Thread> _threadList = new ArrayList<>();
然后我将线程添加到列表中
for (int i = 0; i < 10; i++) {
_threadList.add(new Thread() {
@Override
public void run() {
_threadGate.await();
//long processing code
所以在线程准备好后我启动它们,它们同时启动很重要(好吧几乎,循环需要时间,即使它是 0.01 毫秒):
for (int i = 0; i < _threadList.size(); i++) {
_threadList.get(i).start();
}
现在,主线程x
的结尾是这样的:
}, 0, repeatTimer, TimeUnit.SECONDS);
如果 repeatTimer
是 300
这意味着它将在 5 分钟后再次启动 10 个线程。
10 个线程完成的时间未知,但不到 5 分钟。肯定在 2 到 4 分钟之间。
我想达到的目标
10 个线程完成后,重新启动 X,但延迟 5 秒。
为此,我一直在考虑将 repeatTimer
值设置为 10 个线程经过的时间 + 5 秒(我不知道该怎么做,我不知道最后一个线程何时完成其任务),但这是正确的?或者有其他方法吗?
我不认为这里有 SchedulingExecutorService
的必要性。您可以等待所有线程使用 CountDownLatch 完成它们的工作。
这是一个简单的例子:
while (!stopped) {
CountDownLatch latch = new CountDownLatch(N);
// create and start your threads
latch.await(); // this method blocks until each Thread calls countDown()
// wait here 5 seconds if you want
}
在每个线程的最后一个动作中递减锁存器:
public void run() {
_threadGate.await();
// thread actions
latch.countDown();
}