java,queue ,线程池控制线程做任务
时间: 2023-07-06 09:43:19 浏览: 154
Java中可以通过使用队列和线程池来实现任务队列和多线程的并发处理。具体实现可以按照以下步骤:
1. 创建一个阻塞队列,例如:BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
2. 创建一个线程池,例如:
```
int numThreads = 4;
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
```
3. 向线程池中提交任务,例如:
```
for (int i = 0; i < 10; i++) {
executor.submit(new Task(i));
}
```
4. 等待所有任务执行完毕,例如:
```
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
```
完整代码示例如下:
```
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class TaskQueueDemo {
public static void main(String[] args) throws InterruptedException {
int numThreads = 4;
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();
ExecutorService executor = Executors.newFixedThreadPool(numThreads);
// 提交任务到线程池中
for (int i = 0; i < 10; i++) {
executor.submit(new Task(i));
}
// 关闭线程池
executor.shutdown();
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
}
class Task implements Runnable {
private final int taskId;
public Task(int taskId) {
this.taskId = taskId;
}
public void run() {
System.out.println("Task #" + taskId + " is running.");
}
}
```
在这个示例中,我们创建了一个线程池,其中包含4个工作线程。我们向线程池中提交了10个任务,并等待所有任务执行完毕后关闭线程池。在任务执行过程中,我们通过输出信息来模拟任务的执行过程。
阅读全文