实用的多线程

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程
 *
 * @author 你哥
 * <p>
 * 2999年1月1日
 */
public class CountDownLatchTest {
    /**
     * – the number of threads in the pool
     */
    private static final int THREAD_NUM = 5;

    /**
     * 实现多线程的基本方法之一
     */
    class SubRunner implements Runnable {
        // task 可以是你的类
        String task;
        CountDownLatch latch;

        public SubRunner(String task, CountDownLatch latch) {
            this.task = task;
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                // 获取正在执行任务的线程
                Thread thread = Thread.currentThread();
                // 获取线程的名称
                String threadName = thread.getName();
                // 这里处理你的业务
                System.out.println(task + "," + threadName + ",start");
                Thread.sleep(5000);
                System.out.println(task + "," + threadName + ",end");
            } catch (InterruptedException e) {
                System.out.println("error-" + task);
                throw new RuntimeException(e);
            } finally {
                // countDown一定要执行
                latch.countDown();
            }
        }
    }

    /**
     * 实现多线程打印出一个数组
     */
    private void printArrays() {
        List<String> tasks = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8");
        CountDownLatch latch = new CountDownLatch(tasks.size());

        // 开始
        ExecutorService pool = Executors.newFixedThreadPool(THREAD_NUM);
        for (String task : tasks) {
            pool.execute(new SubRunner(task, latch));
        }
        pool.shutdown();
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        CountDownLatchTest t = new CountDownLatchTest();
        t.printArrays();
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值