JAVA线程池中注意的地方

假设有一个小程序,读取10W条Excel数据,开启线程池往外请求HTTP数据

然后接收返回值写到新建excel中,用于给业务人员统计接口调用成功率

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

public class TestExecutor2
{
	public static void main(String[] args)
	{
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		for(int i=0 ; i<10; i++)
		{
			executorService.submit(new MyHandler());
		}
		executorService.shutdown();
		System.out.println("全部子任务执行完毕,开始写入Excel");
	}
}

class MyHandler implements Runnable
{
	@Override
	public void run()
	{
		try
		{
			Thread.sleep(1000); //模拟请求HTTP
			System.out.println(Thread.currentThread().getName()+"->执行完毕");
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}

输出结果:

112640_wKMM_2338224.png

子任务还没执行完毕,那么问题就是怎么等待全部子任务执行完毕

看代码:

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

public class TestExecutor
{
	public static void main(String[] args)
	{
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		for(int i=0 ; i<10; i++)
		{
			executorService.submit(new Handler());
		}
		executorService.shutdown();
		while( ! executorService.isTerminated())
		{
			//不做任何操作
		}
		System.out.println("全部子任务执行完毕");
	}
}

class Handler implements Runnable
{
	@Override
	public void run()
	{
		try
		{
			Thread.sleep(1000);
			System.out.println(Thread.currentThread().getName()+"->执行完毕");
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}
}

112746_g3mc_2338224.png

这就OK了。

但是 除了这种方式 Java current包还提供了另外一种方法,就是闭锁

代码如下:

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

public class Testbisuo
{
	public static void main(String[] args)
	{
		CountDownLatch countDownLatch = new CountDownLatch(10);
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 10; i++)
		{
			executorService.submit(new Handler1(countDownLatch));
		}
		executorService.shutdown(); //阻止提交新线程
		try
		{
			countDownLatch.await(); //使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		System.out.println("全部子任务执行完毕");
	}
}

class Handler1 implements Runnable
{

	private CountDownLatch countDownLatch;

	public Handler1(CountDownLatch countDownLatch)
	{
		this.countDownLatch = countDownLatch;
	}

	@Override
	public void run()
	{
		try
		{
			Thread.sleep(3000); //模拟耗时请求操作
			System.out.println(Thread.currentThread().getName() + "->任务执行完毕");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		countDownLatch.countDown();  //递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
	}
}

运行结果:

113732_T3xD_2338224.png

转载于:https://my.oschina.net/u/2338224/blog/1456715

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值