手动创建线程池,效果会更好哦。
时间: 2023-07-17 14:09:23 浏览: 106
确实,手动创建线程池可以更好地控制线程的数量和执行方式。以下是一个使用手动创建线程池的 CountDownLatch 示例:
```java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int taskCount = 3;
CountDownLatch latch = new CountDownLatch(taskCount);
ExecutorService executor = createThreadPool(taskCount);
for (int i = 0; i < taskCount; i++) {
executor.submit(new Task(latch));
}
latch.await();
System.out.println("All tasks have finished, now executing main task.");
executor.shutdown();
}
static ExecutorService createThreadPool(int threadCount) {
return Executors.newFixedThreadPool(threadCount);
}
static class Task implements Runnable {
private CountDownLatch latch;
public Task(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println("Task started: " + Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println("Task finished: " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
```
在这个例子中,我们通过 `createThreadPool()` 方法手动创建了一个固定大小的线程池,并将线程池作为参数传递给 `ExecutorService`。这样我们就可以更好地控制线程池的行为,例如指定线程池的大小等。其余部分的逻辑和之前的例子相同。
阅读全文