import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Processor implements Runnable {
private CountDownLatch latch;
public Processor(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
System.out.println("Started.");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
// -----------------------------------------------------
public class App {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(5); // coundown from 5 to 0
ExecutorService executor = Executors.newFixedThreadPool(2); // 2 Threads in pool
for(int i=0; i < 10; i++) {
executor.submit(new Processor(latch)); // ref to latch. each time call new Processes latch will count down by 1
}
try {
latch.await(); // wait until latch counted down to 0
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Completed.");
}
}输出:
开始完成`开始启动
在上述代码“完成”后,应打印6次“启动”作为锁存计数下降到5- 0,为什么总是第7次或第8次?我理解错了吗?
发布于 2018-05-31 15:56:01
您的线程池大小为2,Processor线程执行时间为3秒。
Processors线程被启动,两个Started都打印出来,3秒后就完成了。Started并在3秒后完成。Started和3秒后,当其中一个(或两者都完成)完成。在这一点上,有许多事情将在大致相同的时间内发生(所以顺序是随机的):1. The main thread resumes and prints `Completed`
2. 7th `Processor` thread is started and prints `Started`
3. 8th `Processor` thread is started and prints `Started`
因此,Completed总是前面有6,7或8 Started打印输出。
发布于 2018-05-31 15:51:30
因此,CountDownLatch并不保证它将恢复父线程(这里我指的是您调用latch.await();的线程),一旦计数下降到0,它就会立即执行。所以,当倒计时到0时会发生什么?这意味着现在父线程可以恢复它的工作,这并不意味着它就会得到CPU。因此,它可以恢复,这并不意味着CPU调度父线程一开始倒计时到0。如果有其他线程,那么这些线程有可能在父线程之前执行。在您的示例中,它确保它不会执行before 5 Started 5 time printing Started,但是在打印5倍数Started之后,它会执行ensure,这将是exactly。您还可以在特定的代码执行时观察到,Completed是在所有Started打印结束时打印的。
https://stackoverflow.com/questions/50628056
复制相似问题