从散列映射

时间:2017-02-19 13:19:40

标签: java

我有一个hashmap,我想从中删除一个特定的运行线程,我希望线程继续做一些进程,然后它将被销毁,任何人都知道当从hashmap中删除正在运行的线程时会发生什么?

2 个答案:

答案 0 :(得分:3)

  

任何人都知道从hashmap中删除正在运行的线程会发生什么?

线程将继续运行,直到完成其run方法。换句话说,它将在完成后完成。

参考:Life cycle of a thread in Java

额外:

以下示例也是如此。

new Thread(runnableObject).start();

此线程将在后台运行,直到runnableObject终止。

答案 1 :(得分:1)

同意,您的主题将继续运行,直到方法运行()结束。

试试这段代码:

    //Create the HashMap
    HashMap<String, Thread> map = new HashMap<String, Thread>();

    //Create a task
    Runnable task = () -> {
        while (true) {
            System.out.println("Tick " + System.currentTimeMillis());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    //Create a thread with the task
    Thread t = new Thread(task);

    //Add this thread into the map
    map.put("KEY", t);

    //Start this thread
    t.start();

    //Add this thread into the map
    map.remove("KEY");
相关问题