public class thread extends Thread {
static volatile boolean done = false;// volatile keyword is used
@Override
public void run() {
while (!done) {
for (int i = 1; i < 10; i++) {
try {
thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(currentThread());
System.out.println("1st thread>> " + i);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread th = new Thread(new thread(),"mythread");
th.start();
for (int i = 1; i < 10; i++) {
thread.sleep(400);
System.out.println(currentThread());
System.out.println("2nd thread>> " + i);
if (i == 4) {
done = true;// safe way to stop a thread
break;
}
}
}
}
我使用揮發性靜態變量here.Is它一個安全的方式來停止一個線程,也 當我打印currentThread()方法,我得到這樣的主題輸出[MyThread的, 5,主] 5和主要指什麼?安全的方式來停止一個線程在java中
您在這裏提出兩個問題。 :-) – 2011-12-27 22:25:41
大聲笑似乎我正在爲stackoverflow保存一些數據庫空間。我爲他們扮演祕密的聖誕老人;) – Nav 2011-12-27 22:31:21
那麼,你的第二個問題是藏在底部,很可能被忽略或回答,另一個被忽略。 (例如,Eric Rosenburg的答案)爲了獲得更有針對性的答案,而不是浪費人們的時間(包括你自己的時間),下次你應該考慮提出兩個單獨的問題。數據庫空間便宜;時間不是。這只是不請自來(但希望有幫助)的建議,而不是譴責或批評。 – 2011-12-27 22:35:52