这个问题发布在某个网站上.我没有在那里找到正确的答案,所以我再次在这里发布.
public class TestThread {
public static void main(String[] s) {
// anonymous class extends Thread
Thread t = new Thread() {
public void run() {
// infinite loop
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// as long as this line printed out, you know it is alive.
System.out.println("thread is running...");
}
}
};
t.start(); // Line A
t = null; // Line B
// no more references for Thread t
// another infinite …Run Code Online (Sandbox Code Playgroud) 在下面的示例中,新的Thread()没有任何引用.它是否有可能被垃圾收集在它下面?也没有扩展Thread类或实现runnable,我们如何创建一个线程?
public class TestFive {
private int x;
public void foo() {
int current = x;
x = current + 1;
}
public void go() {
for(int i = 0; i < 5; i++) {
new Thread() {
public void run() {
foo();
System.out.print(x + ", ");
}
}.start();
}
}
public static void main(String args[]){
TestFive bb = new TestFive();
bb.go();
}
}
Run Code Online (Sandbox Code Playgroud) 我想在广播接收器中维护一个哈希表.如果我理解BroadcastReceiver的生命周期,它可能会被杀死,消灭我的成员变量.从BroadcastReceiver中之前的onReceive运行中检索哈希表的理想策略是什么?