countDownLatch.await(1, TimeUnit.SECONDS)的用法

k10509806 2017-05-17 03:54:20

ExecutorService service = Executors.newFixedThreadPool(1);

try
{


CountDownLatch countDownLatch = new CountDownLatch(1);

// 执行
service.execute(new ApplyCallable(call, logisticsContext, response, countDownLatch));

try
{
if(countDownLatch.await(1, TimeUnit.SECONDS))
{
// 不超时
return response;
}
}
catch (Exception e)
{
// ignore exception
}

// 来到这里表示超时
// throw new TimeoutException("send request timeout");
logger.error("######耗时申请跟踪号######", new String[][]{{"运输方式", transportationMode.getTransportationModeChinese()}});


}
finally
{
service.shutdown();
}


为什么超过1秒,这个service.shutdown了,里面的ApplyCallable还可以继续进行,没有关闭掉
...全文
1716 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
OPPPPOP 2017-05-18
  • 打赏
  • 举报
回复
逻辑上应该是这样的 try { Thread.sleep(5 * 1000); countDownLatch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); //interrupt 所以返回 return; } System.out.println("====继续进行======"); service.shutdown 改为 service.shutdownNow();
k10509806 2017-05-18
  • 打赏
  • 举报
回复
一直在调整代码中,重未成功
k10509806 2017-05-17
  • 打赏
  • 举报
回复

@Override
        public void run()
        {
            try
            {
                Thread.sleep(5 * 1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

            try
            {
                System.out.println("====继续进行======");
            }
            finally
            {
                countDownLatch.countDown();
            }

        }

java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.bessky.pss.portal.business.logistics.util.TrackNumberUtils$ApplyCallable.run(TrackNumberUtils.java:258)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at java.lang.Thread.run(Thread.java:745)
[bessky_it][ERROR][2017-05-17 16:16:02] | PSS | ######耗时申请跟踪号###### | 运输方式=京华达香港平邮(华南快速小包平邮), | com.bessky.pss.portal.business.logistics.util.TrackNumberUtils.applyTrackingNumber(TrackNumberUtils.java:208) 
====继续进行======
k10509806 2017-05-17
  • 打赏
  • 举报
回复
还是不行,里面的ApplyCallable会继续进行。我的理想效果的是,超时了,里面的线程就不要继续进行了
李德胜1995 2017-05-17
  • 打赏
  • 举报
回复
使用shutdownNow()试试。。。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧