zoukankan      html  css  js  c++  java
  • Java深入学习20:synchronized

    Java深入学习20:synchronized

    先看一个没有synchronizd修饰的普通方法

    public class SynTest implements  Runnable {
        private static int count ;
        public SynTest() {
            this.count = 0;
        }
        @Override
        public void run() {
            for(int i=0; i<5; i++){
                System.out.println(Thread.currentThread().getName() + ": " +(++count));
            }
        }
        public static void main(String[] args) {
            SynTest synTest = new SynTest();
            Thread thread1 = new Thread(synTest, "thread1");
            Thread thread2 = new Thread(synTest, "thread2");
            thread1.start();
            thread2.start();
        }
    }
    ---------------------日志--------------------------
    thread1: 1
    thread2: 1
    thread1: 2
    thread2: 3
    thread2: 5
    thread2: 6
    thread1: 4
    thread2: 7
    thread1: 8
    thread1: 9

    问题:两个线程并发,竞争资源,导致(1)获取相同的值(thread1: 1和thread2: 1); (2)输出结果顺序不可控

    1- 修饰一个代码块

    public class SynTest2 implements  Runnable {
        private static int count ;
        public SynTest2() {
            this.count = 0;
        }
        @Override
        public void run() {
            synchronized (this){
                for(int i=0; i<5; i++){
                    System.out.println(Thread.currentThread().getName() + ": " +(++count));
                }
            }
        }
        public static void main(String[] args) {
            //方式1
            SynTest2 synTest = new SynTest2();
            Thread thread1 = new Thread(synTest, "thread1");
            Thread thread2 = new Thread(synTest, "thread2");
            thread1.start();
            thread2.start();
    
            //方式2
            SynTest2 synTest1 = new SynTest2();
            SynTest2 synTest2 = new SynTest2();
            Thread thread3 = new Thread(synTest1, "thread3");
            Thread thread4 = new Thread(synTest2, "thread4");
            thread3.start();
            thread4.start();
        }
    }
    ----------------------单独执行方式1日志----------------------
    thread1: 1
    thread1: 2
    thread1: 3
    thread1: 4
    thread1: 5
    thread2: 6
    thread2: 7
    thread2: 8
    thread2: 9
    thread2: 10
    ----------------------单独执行方式2日志----------------------
    thread3: 1
    thread4: 2
    thread3: 3
    thread4: 4
    thread3: 5
    thread3: 7
    thread3: 8
    thread4: 6
    thread4: 9
    thread4: 10

    END

  • 相关阅读:
    [转]Javascript中prototype和constructor详解
    [转]SCIM输入启动遭遇“Failed to load x11 FrontEnd module. ”错误
    [转]搭建高效的symbols服务器
    编译 boost 1.52.0
    opensuse 11.4 安装slickedit 2012 完美支持中文
    【转】MyEclipse 6.5 大提速
    [转]VS2005生成pdb签名的问题
    理解泛型 从需求演变开始
    数学中一个很简单的组合 但用程序如何去实现呢?
    从零开始开发服务器控件
  • 原文地址:https://www.cnblogs.com/wobuchifanqie/p/12758338.html
Copyright © 2011-2022 走看看