监控线程执行

Monitoring Thread Execution

我有下面的代码,首先我创建一个按需数据库连接,然后与多个线程共享它。这工作正常。现在,我想知道是否可以跟踪是否所有使用此数据库连接的线程都已完成执行,以便我可以关闭数据库连接。任何关于如何实现这一目标的指导都会有所帮助。

    Connection connection = null;
    Properties connectionProperties = getProperties();

    for (int reqIdx = 0; reqIdx < requests.length(); reqIdx++) { 
            connection = DBonnection.getConnection(connectionProperties); 
            ConnectorRunner connectorRunner = null;
            try {
                connectorRunner = new ConnectorRunner(someConnector);               
                connectorRunner.setDBConnection(connection);

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

            executorService.execute(connectorRunner);
    }

除上述评论外,如果您希望在所有线程完成后执行某些操作,您可以采用以下任一方法。

ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
    es.execute(new Runnable() { /*  your task */ });
es.shutdown();
boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES);
// all tasks have finished or the time has been reached.

for (Thread thread : threads) {
    thread.join();
}

请注意,第二种方法会阻塞当前线程。

最简单的方法是使用标准 JDK 设施中的 CountDownLatch。在你的主线程中做

CountDownLatch doneSignal = new CountDownLatch(requests.length());

for (Request req : requests) {
  ConnectorRunner connectorRunner = new ConnectorRunner(doneSignal);
  connectorRunner.setConnection(DBonnection.getConnection());
  executorService.execute(connectorRunner);
}

doneSignal.await();
DBonnection.dispose();

ConnectorRunner 完成后必须简单地调用 doneSignal.countDown()