该程序的结果为什么会是
2000
1000
1000
我的理解是这样的!不管线程1还是线程2优先执行,是不是主线程都能优先输出System.out.println(tt.b);
这样应该能看到100的值。但是为什么每次都是这个结果?sleep不是不释放锁吗?谁可以给个详细的解释?谢谢!
- Java code
public class TT implements Runnable{ int b = 100; public synchronized void run(){ try { modify_1(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public synchronized void modify_1() throws InterruptedException{ b=1000; Thread.sleep(5000); System.out.println(b); } public synchronized void modify_2() throws InterruptedException{ Thread.sleep(2500); b=2000; System.out.println(b); } public static void main(String[] args) throws InterruptedException { TT tt = new TT(); Thread th = new Thread(tt); th.start(); tt.modify_2(); System.out.println(tt.b); }}
------解决方案--------------------------------------------------------
主线程执行到。
th.start();
时候。由于线程的启动需要时间。
在启动的这个时间内。
tt.modify_2();
会被执行。 可是.modify_2 中 Thread.sleep(2500); 这时的 b 还是 100
要睡 2500 秒。由于使用了同步所以其他线程也只有等待,直到主线程把 modify_2
执行完。输出 2000 . 这时 th已经启动 并立刻把 的值修改为 b=1000; 并去睡。
主线程会在这个时候 执行 System.out.println(tt.b); 输出 1000;
等 modify_1() 睡醒后 再输出 1000;
所以中间那个 1000 是 System.out.println(tt.b); 输出 的。
最后哪个 1000 是 modify_1() 输出的。
又只有 10 分 呵呵!