假设有一个小程序,读取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();
}
}
}
输出结果:
子任务还没执行完毕,那么问题就是怎么等待全部子任务执行完毕
看代码:
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();
}
}
}
这就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(); //递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
}
}
运行结果: