簡體   English   中英

ConcurrentHashMap刪除線程問題

[英]ConcurrentHashMap removing thread issue

我現在正在使用Java ConcurrentHashMap做一些事情。 我在多線程環境中遇到了一些麻煩。

我的代碼是:1.將Runnable對象添加到ConcurrentHashMap。

private Map<String, ScheduledFuture<?>> scheduledTasks = new ConcurrentHashMap<>();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        // TODO Auto-generated method stub
        AA();
    }
};
ScheduledFuture<?> task = taskScheduler.scheduleAtFixedRate(runnable, 10); 
scheduledTasks.put(taskId, task);
  1. 將Runnable對象刪除到ConcurrentHashMap。
    if (scheduledTasks.get(taskId) != null && !"".equals(scheduledTasks.get(taskId))
    {
        scheduledTasks.get(taskId).cancel(true);
        scheduledTasks.get(taskId).remove();
    }

僅添加或刪除不會造成問題,並且如果我將scheduledTasks.keySet()打印到控制台或日志文件,它將打印正確的結果。

但是,問題在於,可運行對象從Map中刪除后,某些可運行對象仍在運行(即使Map不再具有該可運行對象!)。

我真的不確定這是什么問題。 我對“ Java多線程環境”缺乏了解嗎? 或者...此問題與ScheduledFuture有關?

您也可以按照以下方式進行操作:

ExecutorService exe = Executors.newFixedThreadPool(10);
CountDownLatch taskLatch = new CountDownLatch(10);
List<Callable Interface Instance> loadingTasks = new ArrayList<Callable Interface Instance>();
//create instance of Callable Interface Instance
loadingTasks.add(task);// where task will be Callable Interface Instance/reference name

List<Future<Boolean>> futures = exe.invokeAll(loadingTasks);
boolean complete = taskLatch.await(5, TimeUnit.MINUTES); //waiting for tasks to be completed

for (Future<Boolean> f : futures) {
taskComplete = f.get(); //get callable interface instance call method return value
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM