Java并发编程:线程池、定时任务示例

原创 刺骨的言语ヽ痛彻心扉 2024-11-14 17:09 111阅读 0赞

在Java并发编程中,线程池和定时任务是两种常见的多线程管理方式。

  1. 线程池
    线程池是一种资源池化管理模式。创建一个线程池后,可以向这个池提交任务,这些任务会被线程池中的线程执行。

示例代码(使用ThreadPoolExecutor):

  1. import java.util.concurrent.*;
  2. public class ThreadPoolExample {
  3. public static void main(String[] args) {
  4. // 创建线程池,固定大小为5个线程
  5. ExecutorService executor = Executors.newFixedThreadPool(5);
  6. // 提交任务到线程池
  7. for (int i = 0; i < 10; i++) {
  8. Runnable task = () -> {
  9. System.out.println("Task " + i + " is executed by thread: " + Thread.currentThread().getName());
  10. };
  11. executor.execute(task);
  12. }
  13. // 关闭线程池,释放资源
  14. executor.shutdown();
  15. }
  16. }
  1. 定时任务
    在Java中,我们可以使用java.util.TimerTimerTask来实现定时任务。

示例代码:

  1. import java.util.Timer;
  2. import java.util.TimerTask;
  3. public class TimerExample {
  4. public static void main(String[] args) {
  5. // 创建一个定时器
  6. Timer timer = new Timer();
  7. // 定义定时任务
  8. TimerTask task = new Task("Every 5 seconds", 5000); // 每5秒执行一次
  9. // 将定时任务添加到定时器中
  10. timer.schedule(task, 0);
  11. // 关闭定时器,停止定时任务
  12. try {
  13. timer.cancel();
  14. System.out.println("Timer cancelled.");
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. static class Task extends TimerTask {
  20. private String taskName;
  21. private long delay;
  22. public Task(String name, long delay) {
  23. this.taskName = name;
  24. this.delay = delay;
  25. }
  26. @Override
  27. public void run() {
  28. System.out.println("Timer task executed: " + taskName);
  29. }
  30. }
  31. }

以上代码展示了如何创建线程池进行任务提交,以及如何使用java.util.TimerTimerTask实现定时任务。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,111人围观)

还没有评论,来说两句吧...

相关阅读