Java线程池简单应用

本文通过一个示例展示了如何使用Java Collections.synchronizedList确保线程安全,以及如何利用ExecutorService创建线程池并发执行任务。实验中观察到线程轮流打印List中的元素,体现了多线程的基本操作。
摘要由CSDN通过智能技术生成

Demo:

 public void testThread() {
        List<String> test = new ArrayList<>();
        int i = 0;
        while (i < 10001) {
            i++;
            test.add(i + "");
        }
        //给List加锁,不加会丢数据
        List<String> thread = Collections.synchronizedList(test);
        //创建线程池
        ExecutorService exec = Executors.newFixedThreadPool(3);
        thread.forEach(u -> {
            exec.execute(() -> {
                System.out.println("线程:"+Thread.currentThread().getName());
                System.out.println("thread:"+u);
            });
        });
        //任务结束关闭线程池
        exec.shutdown();
        //判断线程池是否结束,不加会直接结束方法
        while (true) {
            if (exec.isTerminated()) {
                break;
            }
        }
    }

运行结果:

线程:pool-1-thread-2
thread:2
线程:pool-1-thread-2
thread:4
线程:pool-1-thread-2
thread:5
线程:pool-1-thread-1
thread:1
线程:pool-1-thread-2
thread:6
线程:pool-1-thread-3
thread:3
线程:pool-1-thread-2
thread:8
线程:pool-1-thread-1
thread:7
线程:pool-1-thread-2
thread:10
线程:pool-1-thread-3
thread:9
线程:pool-1-thread-2
thread:12
线程:pool-1-thread-1
thread:11
线程:pool-1-thread-2
thread:14
线程:pool-1-thread-3
thread:13
线程:pool-1-thread-2
thread:16
线程:pool-1-thread-1
thread:15
线程:pool-1-thread-2
thread:18
线程:pool-1-thread-3
thread:17
线程:pool-1-thread-2
thread:20
线程:pool-1-thread-1
thread:19
线程:pool-1-thread-2
thread:22
线程:pool-1-thread-3
thread:21
线程:pool-1-thread-2
thread:24
线程:pool-1-thread-1
thread:23
线程:pool-1-thread-2
thread:26
线程:pool-1-thread-3
thread:25
线程:pool-1-thread-2
thread:28
线程:pool-1-thread-1
thread:27
线程:pool-1-thread-2
thread:30
线程:pool-1-thread-3
thread:29
线程:pool-1-thread-2
thread:32
线程:pool-1-thread-1
thread:31
线程:pool-1-thread-2
thread:34
......
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值