线程池ThreadPoolExecutor的例子,Executors.newFixedThreadPool实现

  通过源码可以看到,本质上,Executors.newSingleThreadExecutor();或者Executors.newFixedThreadPool(args);等等,都是在new ThreadPoolExecutor();只是给ThreadPoolExecutor传递参数不通罢了。

最近项目中有这样一个功能:需要短时间内调用外部接口发送大量短信。于是想到了线程池。发送短信有多个账号,并且每个账号也可以多个线程同步进行,由于线程池这块之前用的不多,所以先写了个例子试试:

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import utils.RandomUtils;

public class ThreadPool1 {
	public static void main(String[] args) {
<span style="white-space:pre">		</span>// 创建固定大小的线程池
		ExecutorService pool = Executors.newFixedThreadPool(3);

		for (int i = 0; i < 100; i++) {
			Thread t10 = new Thread(new MyTest());
			pool.execute(t10);
		}

		pool.shutdown();
	}
}

class MyTest implements Runnable {

	// 模拟存储可用的短信发送账号
	protected static ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
	static {
		map.put("key1", "account1");
		map.put("key2", "account2");
		map.put("key3", "account3");
	}

	@Override
	public void run() {
		String key = null;
		String value = null;

		try {
			synchronized (MyTest.class) { // 避免多线程并行key可能取到null
				key = RandomUtils.getRandomKeyFromMap(map); // 从map随机获取一个key
				value = map.get(key);
				map.remove(key);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println(key + "  " + map.size());
		}

		System.out.println("use key:" + key + " value:" + value);
		try {
			Thread.sleep(1000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			map.put(key, value);
			System.out.println("back " + key + "  size:" + map.size());
		}
	}
}


模拟的3个账号,3个线程;前面说到一个账号可以多个线程同时发送,只需要把每个账号用不同key往map里多put几个即可。


测试运行无异常。




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值