Java 从hashmap中删除正在运行的线程
我有一个hashmap,我想从中删除一个特定的运行线程,我希望该线程继续执行一些进程,然后它将被销毁,有人知道当运行线程从hashmap中删除时会发生什么吗 有人知道从hashmap中删除正在运行的线程时会发生什么吗 线程将继续运行,直到完成其run方法。换言之,它将在完成时完成 参考: 额外: 在下面的示例中也会发生同样的情况Java 从hashmap中删除正在运行的线程,java,Java,我有一个hashmap,我想从中删除一个特定的运行线程,我希望该线程继续执行一些进程,然后它将被销毁,有人知道当运行线程从hashmap中删除时会发生什么吗 有人知道从hashmap中删除正在运行的线程时会发生什么吗 线程将继续运行,直到完成其run方法。换言之,它将在完成时完成 参考: 额外: 在下面的示例中也会发生同样的情况 new Thread(runnableObject).start(); 此线程将在后台运行,直到runnableObject终止 有人知道从hashmap中删除正在运
new Thread(runnableObject).start();
此线程将在后台运行,直到runnableObject终止
有人知道从hashmap中删除正在运行的线程时会发生什么吗
线程将继续运行,直到完成其run方法。换言之,它将在完成时完成
参考:
额外:
在下面的示例中也会发生同样的情况
new Thread(runnableObject).start();
此线程将在后台运行,直到runnableObject终止。同意,您的线程将继续运行,直到方法运行结束 请尝试以下代码:
//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");
同意,线程将继续运行,直到方法运行结束 请尝试以下代码:
//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");
对线程的引用与Java中的任何其他引用类型没有什么不同。因此,你的意思是线程将不会继续处理,垃圾收集器将清除它?是的。假设该线程没有从任何其他地方引用,并且该线程已经完成了其run方法的执行。对线程的引用与Java中的任何其他引用类型都没有区别。那么你的意思是该线程将不会继续处理,垃圾回收器将丢弃它?是的。假设线程没有从其他任何地方引用,并且线程已经完成了其运行方法的执行。非常感谢。非常感谢。我的代码没有任何问题,我的程序运行良好。我的代码没有任何问题,我的程序运行良好。