本帖最后由 张向辉 于 2013-2-15 20:51 编辑
很多资料上都说sleep 不会释放锁.我做了一个小例子,感觉有点晕- public class Test2 extends Thread {
- int b = 100;
- public void m1() throws InterruptedException {
-
- System.out.println("m1 enter..");
- synchronized (this) {
- System.out.println("m1 enter synchronized block..");
- b = 200;
- Thread.sleep(5000);//?
- System.out.println("b= " + b);
- }
- }
- public void m2() throws InterruptedException {
- System.out.println("m2 enter..");
- b = 500;
- }
- public void run() {
- System.out.println("runing ...");
- try {
- m1();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws InterruptedException {
- Test2 t = new Test2();
-
- t.start();
- Thread.sleep(2000);
- t.m2();
- }
- }
复制代码 输出结果如下:
runing ...
m1 enter..
m1 enter synchronized block..
m2 enter..
b= 500
我怎么感觉最后一行输出 应该是 100呢.还有m1方法进入同步块后居然还执行m2方法了是怎么回事?
如果给m2方法 加 synchronized,结果是我想要的,想不明白....
|
|