线程同步的3种方法_线程同步_线程同步和异步的区别

在后台管理用户信息的时候,经常会用到批量发送提醒消息,首先想到的有:

(1)、循环发送列表,逐条发送。优点是:简单,如果发送列表很少,而且没有什么耗时的操作,是比较好的一种选择,缺点是:针对大批量的发送列表,不可取,耗时,程序会出现严重的阻塞问题。

(2)、使用队列(BlockingQueue),开启多个线程,分为三个部分。一部分负责处理将发送列表放入队列;一部分负责从队列中读取并发送消息;第三部分负责监视队列是否为空及后续的操作。

(3)、以下说到的这种模式,使用Future、Callable来返回发送结果,觉得是一种比较好的方式,很简单代码也很详细,就不介绍了。

代码如下:

public class PublishMsgTest {

//创建固定大小为100 的线程池

private static ExecutorService service = Executors.newFixedThreadPool(100);

//发送消息的业务逻辑方法

public int sendMsg(List receivers,String content){

long begin = System.nanoTime();

AtomicInteger ai = new AtomicInteger(0);

List> list = new ArrayList();

//循环发送消息

for(int i=0;i

Integer receiver = receivers.get(i);

//使用Future,Callable实现发送消息后返回发送结果

Future future = service.submit(new Callable() {

@Override

public Integer call() throws Exception {

//调用相对比较耗时的发送消息接口

Thread.sleep(200);

//发送消息

int resultStatus = sendMsg(receiver,content);

System.out.println(“接收者【”+receiver+”】,发送结果【”+resultStatus+”】”);

return resultStatus;

});

list.add(future);

System.out.println(“———————–“+(System.nanoTime()-begin)/1000_000d+”———————–“);

//循环接收发送结果,相当于一个使线程同步的过程,这个过程是比较耗时的

for(int i=0;i

try {

int resultStatus = list.get(i).get();

if(resultStatus == 0){//发送成功

ai.incrementAndGet();

} catch (Exception e) {

e.printStackTrace();

System.out.println(“发送消息结束,耗时:”+(System.nanoTime()-begin)/1000_000d);

return ai.get();

public static void main(String[] args){

PublishMsgTest pmt = new PublishMsgTest();

//待接收人

List receivers = new ArrayList();

for(int i=0;i

receivers.add(i);

String content = “群发消息_测试代码”;

int successCount = pmt.sendMsg(receivers, content);

System.out.println(“共有【”+receivers.size()+”】接收者,发送成功【”+successCount+”】”);

//完成发送消息

private int sendMsg(Integer receiver, String content) {

if(receiver%2 == 0){//模拟被2整除,即为发送成功

return 0;

return 1;

以上代码的执行结果:

———————–14.786889———————–

接收者【2】,发送结果【0】

接收者【3】,发送结果【1】

接收者【4】,发送结果【0】

接收者【0】,发送结果【0】

接收者【6】,发送结果【0】

接收者【7】,发送结果【1】

接收者【1】,发送结果【1】

接收者【5】,发送结果【1】

接收者【10】,发送结果【0】

接收者【994】,发送结果【0】

接收者【993】,发送结果【1】

接收者【992】,发送结果【0】

接收者【996】,发送结果【0】

接收者【999】,发送结果【1】

接收者【998】,发送结果【0】

接收者【997】,发送结果【1】

发送消息结束,耗时:2033.053433

共有【1000】接收者,发送成功【500】

限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注