作者hikaru4 (光)
看板b96902HW
標題[JAVA] 關於去年考古題的一些問題
時間Mon Jun 16 16:35:31 2008
關於thread的那題
4.Can it be guaranteed that, when the program stops, the value of counter is
0? Please explain your reason briefly (at most 3 lines). [4*(2+3)%]
去年網站上的答案是
4.
(a) No. Main thread以及新產生的thread會交錯執行各自的for statement。
(b) Yes. 因為執行的是run() 而不是start(),事實上第二個thread並沒有產生。
(c) Yes. Main thread以及新產生的thread都鎖住同一Thread3 object。
(d) No. Main thread鎖住Thread4 class,而新產生的thread鎖住Thread4 object。
我自己有一些疑問
首先是題目所說的 when the program stops 應該是指 main 結束的時候對吧!?
假設是指main結束的時候
我自己用程式測試了一下
在main的最後一行加 System.out.println(counter);
如下
class Thread3 implements Runnable{
static int counter = 0;
public static void main(String[] args) {
Thread3 t = new Thread3();
new Thread(t).start();
synchronized (t) {
for (int i = 0; i < 10000; i++) counter++;
}
System.out.println(counter);
}
synchronized public void run() {
for (int i = 0; i < 10000; i++) counter--;
}
}
class Thread4 extends Thread {
int counter = 0;
public static void main(String[] args) {
Thread4 t = new Thread4();
t.start();
synchronized (Thread4.class) {
for (int i = 0; i < 10000; i++) t.counter++;
}
System.out.println(t.counter);
}
synchronized public void run() {
for (int i =0 ; i < 10000; i++) counter--;
}
}
可是實際跑出來的結果Thread3卻不是0
thread4 的 synchronized (Thread4.class) 改成 synchronized (t)
跑出來的結果也不會是0 而跑來的數值大都在9600附近
我自己推測是因為在.start()之後 Thread 並不會 "馬上" 啟動
結果main就用 synchronized (t) 把權限搶走了 一直加到 10000 才釋放
然後在main要結束之前 另一個thread才開始 減減
所以才會造成這樣的結果
不知道這樣對不對 @.@
還是我一開始加的那行 System.out.println就有問題?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.30.98
※ 編輯: hikaru4 來自: 140.112.30.98 (06/16 16:36)