zoukankan      html  css  js  c++  java
  • Java 多线程学习笔记之synchronized

    当学到马士兵老师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

  • 相关阅读:
    Python的logging模块
    Python中的json模块
    Python的re模块
    NoSQL简介
    单例设计模式
    基于配置文件的方式配置AOP
    重用切点表达式
    切面优先级
    返回通知、异常通知、环绕通知
    后置通知
  • 原文地址:https://www.cnblogs.com/Sherlock-J/p/12926090.html
Copyright © 2011-2022 走看看