Java 多线程学习笔记之synchronized

来源:互联网 发布:淘宝质量鉴定什么意思 编辑:程序博客网 时间:2024/06/05 20:21

当学到马士兵老师Java教程的以下代码时,我在想为什么会是这个结果?

public class TT implements Runnable {
    int b = 100;
    
    public synchronized void m1() throws Exception{
        //Thread.sleep(2000);
        b = 1000;
        Thread.sleep(5000);
        System.out.println("b = " + b);
    }
    
    public synchronized void m2() throws Exception {
        Thread.sleep(2500);
        b = 2000;
    }
    
    public void run() {
        try {
            m1();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws Exception {
        TT tt = new TT();
        Thread t = new Thread(tt);
        t.start();
        
        tt.m2();
        System.out.println(tt.b);
    }
}

4

明明有两个synchronized,再加上main,为什么main函数作为主线程却在等待public synchronized void m2()函数执行完后再执行
System.out.println(tt.b);synchronized特性是什么?
想了一下午,逐渐理清了思路,尝试把心得写下来:

其实tt.m2()是mian()线程中的一部分所以m2()函数执行完后再执行System.out.println(tt.b)。在整个程序中只有两个线程:main与t,即只有m1()在其他线程运行着。我是看到synchronized就下意识的以为tt.m2()是单独的一个线程。我有些粗心了。

synchronized总结(转自http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html)

0 0
原创粉丝点击