cn.hutool.core.thread.ThreadUtil使用示例

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 简化了多线程编程的复杂性,使得并发编程更加容易和安全。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

付聪1210

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值