synchronized 的理解

第一种:package com.ucmed.zsyy.util;
 
/**
 * Created by ucmed on 2017/2/8.
 */
public class DirtyRead {
    private String username = "zjkj";
    private String password = "123";
 
    public  synchronized void setValue(String username, String password) {
        System.out.println("set线程:" + Thread.currentThread().getPriority());
        this.username = username;
        try {
            Thread.sleep(2000);
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
        this.password = password;
        System.out.println("setValue最终结果:username = " + username + "  , password = " + password);
    }
 
    public void getValue() {
        System.out.println("get线程:" + Thread.currentThread().getPriority());
        System.out.println("getValue最终结果:username = " + username + "  , password = " + password);
    }
 
    public static void main(String[] args) throws InterruptedException {
        final DirtyRead dr = new DirtyRead();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                dr.setValue("z3", "456");
            }
        });
        System.out.println("主线程:" + Thread.currentThread().getPriority());
        t1.start();
        Thread.sleep(1000);
        dr.getValue();
    }
}
 
第二种:
package com.ucmed.zsyy.util;
 
/**
 * Created by ucmed on 2017/2/8.
 */
public class DirtyRead {
    private String username = "zjkj";
    private String password = "123";
 
    public  synchronized void setValue(String username, String password) {
        System.out.println("set线程:" + Thread.currentThread().getPriority());
        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() {
        System.out.println("get线程:" + Thread.currentThread().getPriority());
        System.out.println("getValue最终结果:username = " + username + "  , password = " + password);
    }
 
    public static void main(String[] args) throws InterruptedException {
        final DirtyRead dr = new DirtyRead();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                dr.setValue("z3", "456");
            }
        });
        System.out.println("主线程:" + Thread.currentThread().getPriority());
        t1.start();
        Thread.sleep(1000);
        dr.getValue();
    }
}
 
 
理解:
这里只有一个对象,一个对象的多个synchronized修饰的方法的情况
上面例子是当get方法加上锁后,要等待set方法执行完后再执行
在方法上加synchronized关键字,持有的锁为当前对象,当一个线程调用了其中一个synchronized的方法后,其他线程再调用该类中其他synchronized修饰的方法会挂起等待,需要等上一个线程执行完,释放锁后,其他调用线程取得锁后才会执行
不是多个锁,是多个synchronized修饰的方法..这些方法是同一个锁

猜你喜欢

转载自blog.csdn.net/hq091117/article/details/79065145