Mục lục
- Giới thiệu về ScheduleThreadPoolExecutor
- Cách sử dụng ScheduleThreadPoolExecutor
- Phân tích mã nguồn ScheduleThreadPoolExecutor
- Thuộc tính chính
- Phương thức schedule
- Phương thức scheduleAtFixedRate và scheduleWithFixedDelay
- Phương thức run
Giới thiệu về ScheduleThreadPoolExecutor
ScheduleThreadPoolExecutor hỗ trợ khả năng thực thi chậm và định kỳ:
- Thực thi chậm: Sử dụng hàng đợi DelayedWorkQueue để quản lý
- Thực thi định kỳ: Sau khi hoàn thành nhiệm vụ, hệ thống sẽ đặt lại thời gian chờ và đưa nhiệm vụ trở lại hàng đợi
Cách sử dụng ScheduleThreadPoolExecutor
Khởi tạo ThreadPool có tham số sẽ gọi phương thức constructor của lớp cha ThreadPoolExecutor:
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory, handler);
}
Constructor này cho phép thiết lập tối đa 3 tham số:
- Số luồng tối thiểu
- Xưởng tạo luồng
- Chiến lược từ chối
Hàng đợi mặc định là DelayedWorkQueue - một hàng đợi không giới hạn. Do đó không cần cấu hình số luồng tối đa, thời gian tồn tại luồng tạm thời...
Ví dụ minh họa
public class TaskSchedulerExample {
public static void main(String[] args) {
ScheduledThreadPoolExecutor taskScheduler = new ScheduledThreadPoolExecutor(
5,
r -> {
Thread thread = new Thread(r);
thread.setName("worker-thread");
return thread;
},
(r, e) -> {
System.err.println("Task rejected: " + e.getMessage());
}
);
// Thực thi ngay lập tức
taskScheduler.execute(() -> {
System.out.println("Immediate task executed at " + System.currentTimeMillis());
});
// Thực thi sau 2 giây
System.out.println("Scheduled task starts at: " + System.currentTimeMillis());
taskScheduler.schedule(() -> {
System.out.println("Delayed task executed at " + System.currentTimeMillis());
}, 2, TimeUnit.SECONDS);
// Thực thi định kỳ
System.out.println("Periodic task starts at: " + System.currentTimeMillis());
taskScheduler.scheduleAtFixedRate(() -> {
System.out.println("Periodic task executed at " + System.currentTimeMillis());
try {
Thread.sleep(3000); // Mô phỏng công việc tốn thời gian
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, 2, 4, TimeUnit.SECONDS);
}
}