美文网首页
Java并发编程(一): synchronized和volati

Java并发编程(一): synchronized和volati

作者: 码农随想录 | 来源:发表于2018-02-07 15:19 被阅读51次

1、概述

1.1、线程安全概念

当多个线程访问某一个类(对象或方法)时,这个对象始终都能表现出正确的行为,那么这个类(对象或方法)就是线程安全的。

1.2、synchronized

synchronized可以在任意对象及方法上加锁,而加锁的这段代码称为"互斥区"或"临界区"

2、synchronized

2.1、synchronized基本使用

package com.yxp.one.sync001;

/**
 * Created by yangxiooping on 2018/2/5.
 */
public class MyThread extends Thread{

    private int count = 5 ;

    //synchronized加锁
    public synchronized void run(){
        count--;
        System.out.println(this.currentThread().getName() + " count = "+ count);
    }

    public static void main(String[] args) {
 
        MyThread myThread = new MyThread();
        Thread t1 = new Thread(myThread,"t1");
        Thread t2 = new Thread(myThread,"t2");
        Thread t3 = new Thread(myThread,"t3");
        Thread t4 = new Thread(myThread,"t4");
        Thread t5 = new Thread(myThread,"t5");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

运行结果.png
  • 分析
    当多个线程访问myThread的run方法时,以排队的方式进行处理(这里排对是按照CPU分配的先后顺序而定的).
    一个线程想要执行synchronized修饰的方法里的代码:
    1 尝试获得锁
    2 如果拿到锁,执行synchronized代码体内容;拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止,而且是多个线程同时去竞争这把锁。(也就是会有锁竞争的问题)

2.2、多个线程多个锁

package com.yxp.one.sync002;

/**
 * Created by yangxiooping on 2018/2/5.
 */
public class MultiThread {
    private int num = 0;

    /** static */
    public synchronized void printNum(String tag){
        try {

            if(tag.equals("a")){
                num = 100;
                System.out.println("tag a, set num over!");
                Thread.sleep(1000);
            } else {
                num = 200;
                System.out.println("tag b, set num over!");
            }

            System.out.println("tag " + tag + ", num = " + num);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //注意观察run方法输出顺序
    public static void main(String[] args) {

        //俩个不同的对象
        final MultiThread m1 = new MultiThread();
        final MultiThread m2 = new MultiThread();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                m1.printNum("a");
            }
        });

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                m2.printNum("b");
            }
        });

        t1.start();
        t2.start();

    }
}
运行结果.png
  • 分析
    多个线程,每个线程都可以拿到自己指定的锁,分别获得锁之后执行synchronized方法体的内容

2.3、对象锁的同步和异步

    public synchronized void method1(){
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public void method2(){
            System.out.println(Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
        
        final MyObject mo = new MyObject();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                mo.method1();
            }
        },"t1");
        
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                mo.method2();
            }
        },"t2");
        
        t1.start();
        t2.start();
        
    }
运行结果.png
  • 分析
    1、 t1线程先持有object对象的Lock锁,t2线程可以以异步的方式调用对象中的非synchronized修饰的方法
    2、t1线程先持有object对象的Lock锁,t2线程如果在这个时候调用对象中的同步(synchronized)方法则需等待,也就是同步。
    同步的目的就是为了线程安全,其实对于线程安全来说,需要满足原子性(同步)和可见性

2.4、脏读

public class DirtyRead {

    private String username = "yxp";
    private String password = "123";

    public synchronized void setValue(String username, String password){
        this.username = username;

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        this.password = password;

        System.out.println("setValue最终结果:username = " + username + " , password = " + password);
    }
  //public synchronized void getValue(){
    public void getValue(){
        System.out.println("getValue方法得到:username = " + this.username + " , password = " + this.password);
    }


    public static void main(String[] args) throws Exception{

        final DirtyRead dr = new DirtyRead();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                dr.setValue("z3", "456");
            }
        });
        t1.start();
        Thread.sleep(1000);

        dr.getValue();
    }   
}
运行结果.png
  • 分析
    在我们对一个对象的方法加锁时候,需要考虑业务的整体性,即为setValue/getValue方法同时加锁synchronized同步关键字,保证业务(service)的原子性,不然会出现业务错误(也从侧面保证业务的一致性)。

2.5、synchronized锁重入

关键字synchronized拥有锁重入的功能,也就是在使用synchronized时,当一个线程得到了一个对象的锁后,再次请求此对象时是可以再次得到该对象的锁。出现异常,锁自动释放。

2.5.1、对象锁重入
public class SyncDubbo1 {
    public synchronized void method1(){
        System.out.println("method1..");
        method2();
    }
    public synchronized void method2(){
        System.out.println("method2..");
        method3();
    }
    public synchronized void method3(){
        System.out.println("method3..");
    }

    public static void main(String[] args) {
        final SyncDubbo1 sd = new SyncDubbo1();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                sd.method1();
            }
        });
        t1.start();
    }
}
运行结果
2.5.2、类锁重入
public class SyncDubbo2 {
    static class Main {
        public int i = 10;
        public synchronized void operationSup(){
            try {
                i--;
                System.out.println("Main print i = " + i);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Sub extends Main {
        public synchronized void operationSub(){
            try {
                while(i > 0) {
                    i--;
                    System.out.println("Sub print i = " + i);
                    Thread.sleep(100);
                    this.operationSup();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                Sub sub = new Sub();
                sub.operationSub();
            }
        });

        t1.start();
    }
}
运行结果
  • 分析
    1、关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当做锁,所以代码中哪个线程先执行synchronized关键字的方法,哪个线程就持有该方法所属对象的锁(Lock),两个对象,线程获得的就是不同的锁,他们互不影响。

2、在静态方法上加synchronized关键字,表示锁定.class类,类一级别的锁(独占.class类)。

2.6、异常释放锁

public class SyncException {

    private int i = 0;
    public synchronized void operation(){
        while(true){
            while(true){
                try {
                    i++;
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + " , i = " + i);
                    if(i == 5){//模拟业务逻辑出现异常,抛出异常,在方法抛出异常的时候会自动解锁
                        throw new RuntimeException();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public synchronized void operation2(){
        try {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + " , i = " + i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        final SyncException se = new SyncException();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                se.operation();
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                se.operation2();
            }
        },"t2");
        t1.start();
        t2.start();
    }
}
运行结果

2.7、synchronized代码块

public class Optimize {
    public void doLongTimeTask(){
        try {
            System.out.println("当前线程开始:" + Thread.currentThread().getName() +
                    ", 正在执行一个较长时间的业务操作,其内容不需要同步");
            Thread.sleep(2000);
            synchronized(this){
                System.out.println("当前线程:" + Thread.currentThread().getName() +
                        ", 执行同步代码块,对其同步变量进行操作");
                Thread.sleep(1000);
            }
            System.out.println("当前线程结束:" + Thread.currentThread().getName() +
                    ", 执行完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        final Optimize otz = new Optimize();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                otz.doLongTimeTask();
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                otz.doLongTimeTask();
            }
        },"t2");
        t1.start();
        t2.start();
    }
}
运行结果
  • 分析
    使用synchronized声明的方法在某些情况下是有弊端的,比如A线程调用同步的方法执行一个很长时间的人物,那么B线程就必须等待比较长的时间才能执行,这样的情况下可以使用synchronized代码块取优化代码执行时间,也就是通常所说的减小锁的粒度。

2.8、synchronized可以使用任意的Object进行加锁

2.8.1、使用非String的常量加锁
public class ObjectLock {

    public void method1(){
        synchronized (this) {   //对象锁
            try {
                System.out.println("do method1..start");
                Thread.sleep(2000);
                System.out.println("do method1..end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void method2(){      //类锁
        synchronized (ObjectLock.class) {
            try {
                System.out.println("do method2..start");
                Thread.sleep(2000);
                System.out.println("do method2..end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    private Object lock = new Object();
    public void method3(){      //任何对象锁
        synchronized (lock) {
            try {
                System.out.println("do method3..start");
                Thread.sleep(2000);
                System.out.println("do method3..end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        final ObjectLock objLock = new ObjectLock();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                objLock.method1();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                objLock.method2();
            }
        });
        Thread t3 = new Thread(new Runnable() {
            public void run() {
                objLock.method3();
            }
        });
        t1.start();
        t2.start();
        t3.start();
    }
}
运行结果
2.8.2、使用String的常量加锁
public class StringLock {

    public void method() {
        //new String("字符串常量")
        synchronized ("字符串常量") {
            try {
                while(true){
                    System.out.println("当前线程 : "  + Thread.currentThread().getName() + "开始");
                    Thread.sleep(1000);
                    System.out.println("当前线程 : "  + Thread.currentThread().getName() + "结束");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        final StringLock stringLock = new StringLock();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                stringLock.method();
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                stringLock.method();
            }
        },"t2");
        t1.start();
        t2.start();
    }
}
运行结果
  • 分析
    特别注意一个问题,使用String的常量加锁,会出现死循环

2.9、锁对象的改变问题

public class ModifyLock {
    private String name ;
    private int age ;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public synchronized void changeAttributte(String name, int age) {
        try {
            System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 开始");
            this.setName(name);
            this.setAge(age);
            System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 修改对象内容为: "
                    + this.getName() + ", " + this.getAge());
            Thread.sleep(2000);
            System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        final ModifyLock modifyLock = new ModifyLock();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                modifyLock.changeAttributte("张三", 20);
            }
        },"t1");
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                modifyLock.changeAttributte("李四", 21);
            }
        },"t2");
        t1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}
运行结果
  • 分析
    当使用一个对象进行加锁的时候,要注意对象本身发生改变的时候,那么持有的锁就不同。如果对象本身不发生改变,那么依然是同步的,即使是对象的属性发生了改变。

2.10、死锁问题

public class DeadLock implements Runnable{

    private String tag;
    private static Object lock1 = new Object();
    private static Object lock2 = new Object();
    public void setTag(String tag){
        this.tag = tag;
    }
    public void run() {
        if(tag.equals("a")){
            synchronized (lock1) {
                try {
                    System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 进入lock1执行");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 进入lock2执行");
                }
            }
        }
        if(tag.equals("b")){
            synchronized (lock2) {
                try {
                    System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 进入lock2执行");
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("当前线程 : "  + Thread.currentThread().getName() + " 进入lock1执行");
                }
            }
        }
    }
    public static void main(String[] args) {
        DeadLock d1 = new DeadLock();
        d1.setTag("a");
        DeadLock d2 = new DeadLock();
        d2.setTag("b");
        Thread t1 = new Thread(d1, "t1");
        Thread t2 = new Thread(d2, "t2");
        t1.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}
运行结果
  • 分析
    t1线程等待t2线程释放lock2锁,t2线程等待t1线程释放lock1锁,从而导致死锁

3、volatile

3.1、基本概念

volatile关键字的主要作用是使变量在多个线程间可见

public class RunThread extends Thread{

    private volatile boolean isRunning = true;
    private void setRunning(boolean isRunning){
        this.isRunning = isRunning;
    }
    public void run(){
        System.out.println("进入run方法..");
        int i = 0;
        while(isRunning == true){
            try {
                Thread.sleep(10);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("循环中...");
        }
        System.out.println("线程停止");
    }
    public static void main(String[] args) throws InterruptedException {
        RunThread rt = new RunThread();
        rt.start();
        Thread.sleep(50);
        rt.setRunning(false);
        System.out.println("isRunning的值已经被设置了false");
    }
}
运行结果
  • 分析
    1、在java中,每一个线程都会有一块工作内存区,其中存放着所有线程共享的主内存中的变量值的拷贝。当线程执行时,他在自己的工作内存中操作这些变量。为了存取一个共享的变量,一个线程通常先获取锁定并去清除它的内存工作区,把这些共享变量从所有线程的共享内存区中正确的装入到他自己所在的工作内存区中,当线程解锁时保证该工作内存区变量的值写回到共享内存中。
    2、一个线程可以执行的操作有:使用(use)、赋值(assign)、装载(load)、存储(store)、锁定(lock)、解锁(unlock)。
    3、主内存(共享内存)可以执行的操作有:读(read)、写(write)、锁定(lock)、解锁(unlock),每个操作都是原子的。
    4、volatile的作用就是强制线程到主内存里去读取变量,而不去线程工作内存区里去读取,从而实现了多个线程间的变量可见。也就是满足线程安全的可见性。

3.2、AtomicInteger

AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。

public class AtomicUse {

    private static AtomicInteger count = new AtomicInteger(0);
    //多个addAndGet在一个方法内是非原子性的,需要加synchronized进行修饰,保证4个addAndGet整体原子性
    public synchronized int multiAdd(){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count.addAndGet(1);
        count.addAndGet(1);//+2
        return count.get();
    }
    public static void main(String[] args) {
        final AtomicUse au = new AtomicUse();

        List<Thread> ts = new ArrayList<Thread>();
        for (int i = 0; i < 5; i++) {
            ts.add(new Thread(new Runnable() {
                public void run() {
                    System.out.println(au.multiAdd());
                }
            }));
        }
        for(Thread t : ts){
            t.start();
        }
    }
}
运行结果

3.3、volatile关键字不具备synchronized关键字的原子性(同步)

public class VolatileNoAtomic extends Thread{
    private static volatile int count;
    // private static AtomicInteger count = new AtomicInteger(0);
    private static void addCount(){
        for (int i = 0; i < 10000; i++) {
            count++ ;
            // count.incrementAndGet();
        }
        System.out.println(count);
    }
    public void run(){
        addCount();
    }
    public static void main(String[] args) {
        VolatileNoAtomic[] arr = new VolatileNoAtomic[100];
        for (int i = 0; i < 10; i++) {
            arr[i] = new VolatileNoAtomic();
        }
        for (int i = 0; i < 10; i++) {
            arr[i].start();
        }
    }
}
运行结果
public class VolatileNoAtomic extends Thread{
    //private static volatile int count;
    private static AtomicInteger count = new AtomicInteger(0);
    private static void addCount(){
        for (int i = 0; i < 10000; i++) {
            //count++ ;
             count.incrementAndGet();
        }
        System.out.println(count);
    }
    public void run(){
        addCount();
    }
    public static void main(String[] args) {
        VolatileNoAtomic[] arr = new VolatileNoAtomic[100];
        for (int i = 0; i < 10; i++) {
            arr[i] = new VolatileNoAtomic();
        }
        for (int i = 0; i < 10; i++) {
            arr[i].start();
        }
    }
}
运行结果
  • 分析
    第一个程序最后结果为84853,比第二个原子操作变量count的结果100000少,说明 volatile关键字不具备synchronized关键字的原子性(同步)

4、最后

这是我在学习synchronized整理的学习笔记,希望能分享出来和大家一起探讨,笔记代码传送门。如果你觉得我的笔记对您有一点帮助,请给我点赞鼓励。谢谢

相关文章

网友评论

      本文标题:Java并发编程(一): synchronized和volati

      本文链接:https://www.haomeiwen.com/subject/ekxizxtx.html