你好,我希望使用静态列表来保存所有正在运行的线程,例如:
public class MyClass {
public static final List<Thread> threads = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
MyClass.threads.add(Thread.currentThread());
try {
Thread.sleep(2000);
} catch (Exception e) {
}
}).start();
for (int i = 0; i < 10; i++) {
if (!threads.isEmpty()) {
Thread t = threads.get(0);
System.out.println(t.isAlive());
}
Thread.sleep(1000);
}
}
}
上面的代码将会打印出:
true
true
false
false
...
预期的结果是在2秒后线程返回。
我的问题是:线程返回后,添加到静态线程列表中的线程是否会消失?即我是否期望看到线程对象在返回后某个时刻变为null?还是我会无限期地看到线程对象?垃圾收集器在这里起作用吗?