假设我有 X 个线程以并行模式运行,同时我希望我的新线程仅在所有 X 个数完成后运行?
问问题
95 次
4 回答
0
for (Thread thread: threads)
thread.join();
new MyNewThread().start()
于 2013-11-02T11:42:13.470 回答
0
如果您需要多个阶段,每个阶段具有不同数量的线程,请使用 aCyclicBarrier
或 a 。Phaser
于 2013-11-02T11:26:05.247 回答
0
您可以使用CountDownLatch
. 只是
n
在 Latch 构造函数中设置- 在每个工作线程使用结束时
yourLatchInstance.countDown()
- 在等待线程使用开始时
await()
。AftercountDown()
将被调用n
次等待线程将是空闲的。
于 2013-11-02T11:26:14.417 回答
0
尝试这个:
public class Main {
/** The initial number of threads launched*/
public static final int INITIAL_THREADS = 10;
/** When less than MIN_THREADS are running, a new Thread is thrown. */
public static final int MIN_THREADS = 5;
/** */
public static final int TOTAL_THREADS_TO_PROCESS = 30;
/** Launches INITIAL_THREADS and ends */
public static void main(String[] args){
for(int i=0; i<INITIAL_THREADS; i++)
new Thread( new MyThread() ).start();
}
}
class MyThread implements Runnable{
/** Stores the number of Threads runnning running. */
private static int threadsRunning = 0;
/** Stores the number of total thread processed. Used as a exit confition */
private static int threadProcessed = 0;
@Override
public void run(){
//With this synchronized block we modify the threadsRunning safely
//synchronized(this) <- Not valid because Threads objects are
// not the same instance.
synchronized(MyThread.class){
threadsRunning++;
threadProcessed++;
System.out.println("Threads running:" + threadsRunning +
", Total Threads processed:" + threadProcessed +".");
}
//Thread Code here. I simulate it with a 10 second sleep.
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Needed to read/write threadsRunning and threadProcessed safely
synchronized(MyThread.class){
threadsRunning--;
if(threadsRunning < Main.MIN_THREADS &&
threadProcessed < Main.TOTAL_THREADS_TO_PROCESS)
new Thread( new MyThread() ).start();
}
}
}
您可以看到在特定时刻,运行的进程少于 5 个。这是因为一个线程结束并且系统继续另一个线程,该线程也在第一个启动的新线程启动之前结束(仍在等待)。如果过程更繁重(在示例中,如果您将 10 秒更改为 100 或更多),则这种可能性较小。
如果您希望使用另一个退出条件,例如,在 run 方法中间计算的变量,请记住将其设为静态,并且对该变量的读/写必须包含在 synchronized(MyThread.class) 块中。
于 2013-11-02T12:33:15.043 回答