cn.hutool.core.thread.ThreadUtil
是 Hutool 工具库中用于简化线程操作的一个实用工具类。以下是一些常用的使用示例:
在公共线程池中执行线程
ThreadUtil.execute(() -> {
// 你的任务代码
System.out.println("任务执行!");
});
执行异步方法并获取返回值
Future<String> future = ThreadUtil.execAsync(() -> {
return "异步任务结果!";
});
// 获取异步任务的结果
System.out.println(future.get());
使用 CountDownLatch
实现线程等待
CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(3);
for (int i = 0; i < 3; i++) {
ThreadUtil.execute(() -> {
// 模拟任务执行
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程 " + Thread.currentThread().getName() + " 执行完毕!");
countDownLatch.countDown();
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕!");
创建并启动一个定时任务
ScheduledThreadPoolExecutor executorService = ThreadUtil.createScheduledExecutor(1);
ThreadUtil.schedule(executorService, () -> {
// 定时执行的任务
System.out.println("定时任务执行:" + LocalDateTime.now());
}, 0, 5, TimeUnit.SECONDS, true);
创建线程工厂
ThreadFactory namedThreadFactory = ThreadUtil.createThreadFactory("my-thread-pool");
创建线程局部变量
ThreadLocal<Integer> threadLocal = ThreadUtil.createThreadLocal(true);
threadLocal.set(1);
System.out.println(threadLocal.get());
安全地挂起当前线程
boolean success = ThreadUtil.safeSleep(1000);
if (!success) {
System.out.println("线程被中断!");
}
获取当前线程组中的所有线程
Thread[] threads = ThreadUtil.getThreads();
for (Thread thread : threads) {
System.out.println(thread.getName());
}
结束线程
public class ThreadInterruptExample {
public static void main(String[] args) {
// 创建一个新线程来执行长时间运行的任务
Thread longRunningTask = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
// 模拟长时间运行的任务
System.out.println("执行长时间运行的任务......");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// 此处捕获InterruptedException,然后退出循环。
System.out.println("任务被中断,停止执行!");
// 返回方法,结束线程
return;
}
}
});
// 启动线程
longRunningTask.start();
// 在主线程中等待几秒钟,然后中断子线程
try {
Thread.sleep(5000);
// 使用ThreadUtil.interrupt来中断线程
ThreadUtil.interrupt(longRunningTask, true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
等待线程结束
public class WaitForThreadToDieExample {
public static void main(String[] args) {
// 创建并启动线程
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("线程执行:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// 如果线程被中断,退出循环。
break;
}
}
});
// 启动线程
thread.start();
// 等待线程结束
ThreadUtil.waitForDie(thread);
// 线程结束后的操作
System.out.println("线程执行完毕!");
}
}
这些示例展示了 ThreadUtil
类提供的一些常用功能,包括线程池管理、异步执行、线程同步、线程中断和等待等。通过这些方法,Hutool 简化了多线程编程的复杂性,使得并发编程更加容易和安全。