2017-02-19 40 views
1

我有一个HashMap删除正在运行的线程,我想从它删除特定正在运行的线程,我想线程继续做一些处理,然后将被销毁,任何人都知道会发生什么时正在运行的线程从散列表中删除?从一个HashMap

+0

甲参照'Thread'是从* Java中的任何其它参考类型*没有什么不同。 – CKing

+0

所以你的意思是线程不会继续处理,垃圾回收器会摆脱它? – stackmalux

+0

是的。如果'Thread'没有被其他地方引用,'Thread'完成执行它的'run'方法。 – CKing

回答

3

的人都知道,当正在运行的线程从HashMap中去掉会发生什么?

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

参考:Life cycle of a thread in Java


额外:

同样的情况在下面的例子。

new Thread(runnableObject).start(); 

这个线程会在后台运行,直到runnableObject终止。

+0

非常感谢所有人。 – stackmalux

+0

不客气。 – Zack

0

同意,你的线程将继续运行,直到方法的run()结束。

尝试此代码:

//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"); 
+0

我的代码没有任何问题,我的程序工作正常。 – stackmalux

+0

非常感谢您分享您的代码。 – stackmalux