Java并发编程:线程池、定时任务示例
在Java并发编程中,线程池和定时任务是两种常见的多线程管理方式。
- 线程池:
线程池是一种资源池化管理模式。创建一个线程池后,可以向这个池提交任务,这些任务会被线程池中的线程执行。
示例代码(使用ThreadPoolExecutor):
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建线程池,固定大小为5个线程
ExecutorService executor = Executors.newFixedThreadPool(5);
// 提交任务到线程池
for (int i = 0; i < 10; i++) {
Runnable task = () -> {
System.out.println("Task " + i + " is executed by thread: " + Thread.currentThread().getName());
};
executor.execute(task);
}
// 关闭线程池,释放资源
executor.shutdown();
}
}
- 定时任务:
在Java中,我们可以使用java.util.Timer
和TimerTask
来实现定时任务。
示例代码:
import java.util.Timer;
import java.util.TimerTask;
public class TimerExample {
public static void main(String[] args) {
// 创建一个定时器
Timer timer = new Timer();
// 定义定时任务
TimerTask task = new Task("Every 5 seconds", 5000); // 每5秒执行一次
// 将定时任务添加到定时器中
timer.schedule(task, 0);
// 关闭定时器,停止定时任务
try {
timer.cancel();
System.out.println("Timer cancelled.");
} catch (Exception e) {
e.printStackTrace();
}
}
static class Task extends TimerTask {
private String taskName;
private long delay;
public Task(String name, long delay) {
this.taskName = name;
this.delay = delay;
}
@Override
public void run() {
System.out.println("Timer task executed: " + taskName);
}
}
}
以上代码展示了如何创建线程池进行任务提交,以及如何使用java.util.Timer
和TimerTask
实现定时任务。
还没有评论,来说两句吧...