首页 > 其他 > 详细

Synchronized的基本使用

时间:2017-10-01 15:05:59      阅读:237      评论:0      收藏:0      [点我收藏+]

/*

对静态方法的同步本质上是对类的同步

(1)修饰普通方法、(2)修饰静态方法、(3)修饰代码块

*/

public class ThreadDemo {
    //public static synchronized void method1()   (2)
    public synchronized void method1() {    (1)

        System.out.println("Method 1 start");
        try {
            // synchronized (this) {   (3)
            System.out.println("Method 1 execute");
            Thread.sleep(3000);
            // }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 1 end");
    }
    
    //public static synchronized void method2()    (2)
    public synchronized void method2() {   (1)
        System.out.println("Method 2 start");
        try {
            // synchronized (this) {    (3)
            System.out.println("Method 2 execute");
            Thread.sleep(1000);
            // }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Method 2 end");
    }

    public static void main(String[] args) {
        final ThreadDemo test = new ThreadDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method1();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                test.method2();
            }
        }).start();
    }
}

Synchronized的基本使用

原文:http://www.cnblogs.com/fwx-jy/p/7617182.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!