java 线程池演示

package javaDemo.threadLocal;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
     * @ClassName: MyThread
     * @Description: 演示开启多线程处理批量数据信息
     * @author dongwei_qi
     * @date 2020-9-23
     *
     */

public class MyThread {

	public static void main(String[] args) throws InterruptedException {
		Long startTime = System.currentTimeMillis();
//		链表队列,初始化800大小
		LinkedBlockingDeque<Runnable> queue = new LinkedBlockingDeque<Runnable>(800);
//		最小线程数、最大线程数、存活时间、单位分、执行队列信息
		ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 10, 80000, TimeUnit.SECONDS, queue);
		int countThread = 10;
//		int listNum = 286;
//		业务数据总数 / 每个线程执行数据量 + (业务总数对 执行线程数取余 ,不能整除增加一个线程进行数据处理)
//		int num = listNum / countThread + (listNum % countThread != 0 ? 1 : 0);
//		计算执行业务所有线程数量,制定每个线程初始化数量根据数量计算所需线程数
		CountDownLatch counLatch = new CountDownLatch(countThread);
//		要进行发送短信的集合
		List<String> list = new ArrayList<String>();
		list.add("11111");
		list.add("222");
		list.add("333");
		for(int i=0;i<countThread;i++ ) {
//			通过构造函数传递数据
			MyThreadRunnable thread = new MyThreadRunnable(list, i,counLatch);
//			执行线程开始
			executor.execute(thread);
		}
//		等待计数器执行完毕,最终为0时说明所有线程执行完毕
		counLatch.await();
//		所有线程执行完毕,关闭线程池
		executor.shutdown();
		Long endTime = System.currentTimeMillis();
		System.out.println(endTime - startTime);
		System.out.println("多线程执行完毕!");
	}
}
package javaDemo.threadLocal;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
     * @ClassName: MyThreadRunnable
     * @Description: 线程执行类
     * @author dongwei_qi
     * @date 2020-9-23
     *
     */

public class MyThreadRunnable implements Runnable
{
	private List<String> list;
	private int size;
	private CountDownLatch counLatch;
	public MyThreadRunnable(List<String> list,int size, CountDownLatch counLatch) {
		this.size = size;
		this.list = list;
		this.counLatch=counLatch;
	}

		@Override
		public void run() {
			try {
				if(!list.isEmpty()) {
					list.forEach(e ->{
						System.out.println(size +"=============开始执行短信、邮件发送!---"+e);
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
//				计数器减一,通知CountDownLatch 
				counLatch.countDown();
			}
		}

}

不足之处,请不吝赐教
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值