Java 多线程应用实例
时间: 2024-04-23 15:19:14 浏览: 98
以下是两个Java多线程应用实例:
1. 任务处理线程池[^1]
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
// 提交任务给线程池处理
for (int i = 0; i < 100; i++) {
final int task = i;
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("Task " + task + " is being processed by thread: " + Thread.currentThread().getName());
// 执行任务的逻辑代码
}
});
}
// 关闭线程池
executor.shutdown();
}
}
```
2. Java Web服务器中的线程池应用
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class WebServerExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
// 接收客户端请求并提交给线程池处理
while (true) {
// 接收客户端请求
Request request = acceptRequest();
// 提交任务给线程池处理
executor.execute(new Runnable() {
@Override
public void run() {
// 处理请求的逻辑代码
processRequest(request);
}
});
}
}
private static Request acceptRequest() {
// 接收客户端请求的逻辑代码
return null;
}
private static void processRequest(Request request) {
// 处理请求的逻辑代码
}
}
```
阅读全文