【问题标题】:What happens to ExecutorService if I stop a running java project如果我停止正在运行的 java 项目,ExecutorService 会发生什么
【发布时间】:2014-06-17 16:48:41
【问题描述】:

当我在 Eclipse 中测试我的代码时,我在控制台中停止了程序,但我发现线程仍在继续工作。我正在尝试创建一个管道来处理我们不断传入的数据。停止程序时如何关闭所有正在运行的线程?

(特别是当我使用无限循环时)

这是我的主要内容:

    public static void main(String[] args) { 

    queue = new ArrayBlockingQueue<StreamQueueItem>(100);       

    LogFileProcessor threadFileProcessor = new LogFileProcessor(queue);
    new Thread(threadFileProcessor).start();

    StreamCoordinator threadStreamCoordinator = new StreamCoordinator(queue);
    new Thread(threadStreamCoordinator).start();

}

基本上第一个线程将 BlockingQueue 加入队列,第二个线程将弹出项保持在队列之外,并选择一个请求发送者来发送请求。

StreamCoordinator的代码:

public StreamCoordinator(BlockingQueue<StreamQueueItem> mQueue) {
    super();
    this.mQueue = mQueue;
    this.mThreadPool = Executors.newFixedThreadPool(ConfigConstants.SENDER_THREDPOOL_SIZE); 
    mBqHelper = new BigqueryHelper(ConfigConstants.PROJECT_ID,ConfigConstants.DATA_SET, ConfigConstants.TABLE_EXISTS);
}

@Override
public void run() {
    StreamQueueItem item = null;

    while(true){
        //wait 1 second for next request
        try {
            Thread.sleep(1 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        item = mQueue.poll();
        if( item != null){
            mThreadPool.execute(new RequestSender(mBqHelper,item));
        }
    }

}

请求发送者:

@Override
public void run() {
    System.out.format("%d is sending request %s . List size: %d %s\n",mSenderId,FormatHelper.currentDate(),mRequestItem.getRowList().size(),mRequestItem.getLogReason().getTableName());
    mBqHelper.submitStreamRequest(mRequestItem.getLogReason().getTableName(), mRequestItem.getRowList());
    System.out.println("# " + mSenderId + " done. " + FormatHelper.currentDate());
}

【问题讨论】:

  • “停止一个java项目”?这需要澄清一下。
  • 如果你杀死了 JVM,线程就不可能还在运行。
  • 我刚刚在 Eclipse 控制台中单击了停止。可能 JVM 没有被杀死,因为 Eclipse 仍然处于打开状态
  • 我觉得我的代码应该有问题,因为我没有通知 JVM 应该停止那些由 mThreadPool 调用的正在运行的线程。但我不知道问题到底出在哪里。
  • “但我不知道问题出在哪里。”我们也没有。

标签: java multithreading executorservice


【解决方案1】:

这是邪恶的代码:

} catch (InterruptedException e) {
    e.printStackTrace();
}

如果您发现InterruptedException,您必须妥善处理它。记录它并忽略它会导致您的程序行为异常。如果告诉您的线程它需要停止(即您按下红色按钮),则该异常是运行时的方式。

尝试对异常做出适当的反应:

} catch (InterruptedException e) {
    return;
}

这是一篇关于这个主题的优秀文章,值得一读:Java theory and practice: Dealing with InterruptedException

【讨论】:

    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    相关资源
    最近更新 更多