在下面的代碼中,我的主要任務是不等待子任務完成其執行。我是Java Thread的新手。所以我無法修復它。我谷歌,發現沒有運氣。請幫我解決這個線程問題。 代碼:Java多線程問題
class ExecutorServiceManager{
public static ExecutorService getExecutor() {
if (executorService == null) {
try {
lock.lock();
if (executorService == null) {
executorService = Executors.newFixedThreadPool(150);
}
} finally {
lock.unlock();
}
}
if(executorService instanceof ThreadPoolExecutor) {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
int corePoolSize = threadPoolExecutor.getCorePoolSize();
int maximumPoolSize = threadPoolExecutor.getMaximumPoolSize();
Logger.info(ExecutorServiceManager.class, "ExecutorInfo: CorePoolSize:%s, MaxPoolSize:%s", corePoolSize, maximumPoolSize);
}
return executorService;
}}
class ServiceImpl{
ExecutorServiceManager executorServiceManager;
private void processConversion(String category, Map<String, String> couchDeltaMap, String processKey, String reqId) {
try {
ProgressVo progressVo = new ProgressVo();
CountDownLatch pgCntxtcountDownLatch = new CountDownLatch(1);
executorServiceManager.getExecutor().submit(new MainTask(category, processKey, pgCntxtcountDownLatch, executorServiceManager, progressVo));
Logger.info(ServiceImpl.class, "ExecutorInfo: CorePoolSize:%s, MaxPoolSize:%s", corePoolSize, maximumPoolSize);
pgCntxtcountDownLatch.await();
} catch(InterruptedException ie) {}
catch(Exception ex) {}
}}
class MainTask implements Runnable{
@Override
public void run() {
executorService = executorServiceManager.getExecutor();
executorService.submit(new SubTask(progressVo, couchDeltaMap, reqId, executorServiceManager));
//I want the below operation to be executed, if and only the subtask completed its execution.
//But the below logger is printing before the subtask completed its execution.
Logger.info(MainTask.class, "It got executed before the subtask completed its processing");
pgCntxtcountDownLatch.countDown();
}}
class SubTask implements Runnable{
@Override
public void run() {
executorService = executorServiceManager.getExecutor();
doSomeProcess;
//It stopped in the middle, and the Main task started executing the remaining operation
}}
雙檢鎖壞了,除非你採取某些步驟,這是不必要的,因爲不管怎樣都不應該使用雙重檢查鎖定。你有沒有采取措施確保不必要的雙重檢查鎖定習慣用法能正常工作? –
如果你是java線程的新手,我會堅持使用基本的線程類。它會迫使你理解機制,然後你可以使用更容易使用的類,如果理解機制 – efekctive