Synchronized简介与使用

1、Synchronized的作用

能够保证在同一时刻最多只有一个线程执行该段代码,已达到保证并发安全的效果。

如果没有Synchronized去保证并发安全,那么程序运行的结果会有差错。

实例代码:

public class MyRunnable implements Runnable{
    private static int a = 0;
    private static MyRunnable run1 = new MyRunnable();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(run1);
        Thread t2 = new Thread(run1);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("最终运算结果=========" + a);
    }

    @Override
    public void run() {
        for(int i = 0; i < 10000; i++)
            a++;
    }
}

实例运行结果为: 最终运算结果=========16079(当然也可以是其他数值,反正就是无法确定)

2、Synchronized的两种用法

1)对象锁:包括方法锁(默认锁对象为this当前实例对象)和同步代码块锁(自己指定所对象)

实例代码(同步代码块锁之锁定this对象):

public class SynchronizedObjectCodeBlock implements Runnable {
    private static SynchronizedObjectCodeBlock synchronizedObjectCodeBlock = new
            SynchronizedObjectCodeBlock();

    @Override
    public void run() {
        synchronized(this) {
            System.out.println("代码块运行开始\t" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("代码块运行结束\t" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(synchronizedObjectCodeBlock);
        Thread t2 = new Thread(synchronizedObjectCodeBlock);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");
    }
}


实例运行结果:

代码块运行开始    Thread-0
代码块运行结束    Thread-0
代码块运行开始    Thread-1
代码块运行结束    Thread-1
程序运行结束

 

示例代码(同步代码块锁之锁定object对象):

public class SynchronizedObjectCodeBlock implements Runnable {
    private static SynchronizedObjectCodeBlock synchronizedObjectCodeBlock = new
            SynchronizedObjectCodeBlock();
    private Object object = new Object();

    @Override
    public void run() {
        synchronized(object) {
            System.out.println("代码块运行开始\t" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("代码块运行结束\t" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(synchronizedObjectCodeBlock);
        Thread t2 = new Thread(synchronizedObjectCodeBlock);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");
    }
}

实例运行结果:

代码块运行开始    Thread-0
代码块运行结束    Thread-0
代码块运行开始    Thread-1
代码块运行结束    Thread-1
程序运行结束

 

实例代码(方法锁):

public class SynchronizedObjectMethod implements Runnable {
    private static SynchronizedObjectMethod synchronizedObjectMethod = new
            SynchronizedObjectMethod();

    @Override
    public void run() {
        test();
    }

    public synchronized void test(){
        System.out.println("test()方法运行开始" + Thread.currentThread().getName());
        System.out.println("test()方法运行结束" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(synchronizedObjectMethod);
        Thread t2 = new Thread(synchronizedObjectMethod);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");
    }
}

运行结果:
test()方法运行开始Thread-0
test()方法运行结束Thread-0
test()方法运行开始Thread-1
test()方法运行结束Thread-1
程序运行结束

2)类锁:指Synchronized修饰静态的方法或指定锁为Class对象

概念:Java类可能有很多个对象,但是只有一个Class对象(举例:Student类可以创建出很多的实例对象,如student1,student2,...,在Java中每一个类都有且只有一个对应的Class对象),

本质:所谓的类锁其实就是类的Class对象的锁,不同的实例之间会产生互斥,

用法和效果:类锁只能在同一时刻被一个对象拥有,即一旦运用了类锁之后,只有一个对象能拥有这个类锁,其他对象如果想要竞争这个类锁会被阻塞

 

形式1:synchronized加在static方法上

实例代码(synchronized加在普通方法上):

public class SynchronizedClassStatic implements Runnable {
    private static SynchronizedClassStatic instance1 = new SynchronizedClassStatic();
    private static SynchronizedClassStatic instance2 = new SynchronizedClassStatic();

    @Override
    public void run() {
        test();
    }

    public synchronized void test(){
        System.out.println("test()方法运行开始\t" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test()方法运行结束\t" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");

    }
}

代码运行结果:
test()方法运行开始	Thread-0
test()方法运行开始	Thread-1
test()方法运行结束	Thread-1
test()方法运行结束	Thread-0
程序运行结束

实例代码(synchronized加在static方法上):

public class SynchronizedClassStatic implements Runnable {
    private static SynchronizedClassStatic instance1 = new SynchronizedClassStatic();
    private static SynchronizedClassStatic instance2 = new SynchronizedClassStatic();

    @Override
    public void run() {
        test();
    }

    public static synchronized void test(){
        System.out.println("test()方法运行开始\t" + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test()方法运行结束\t" + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");

    }
}


代码运行结果:
test()方法运行开始	Thread-0
test()方法运行结束	Thread-0
test()方法运行开始	Thread-1
test()方法运行结束	Thread-1
程序运行结束

形式2:synchronized(*.class) {代码块}

示例代码(synchronized去锁定普通对象)

public class SynchronizedClassClass implements Runnable {
    private static SynchronizedClassClass instance1 = new SynchronizedClassClass();
    private static SynchronizedClassClass instance2 = new SynchronizedClassClass();

    @Override
    public void run() {
        test();
    }

    public void test(){
        synchronized(this) {
            System.out.println("test()方法运行开始\t" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("test()方法运行结束\t" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");
    }
}

代码运行结果:
test()方法运行开始	Thread-0
test()方法运行开始	Thread-1
test()方法运行结束	Thread-0
test()方法运行结束	Thread-1
程序运行结束

代码实例(synchronized去锁定Class对象):

public class SynchronizedClassClass implements Runnable {
    private static SynchronizedClassClass instance1 = new SynchronizedClassClass();
    private static SynchronizedClassClass instance2 = new SynchronizedClassClass();

    @Override
    public void run() {
        test();
    }

    public void test(){
        synchronized(SynchronizedClassClass.class) {
            System.out.println("test()方法运行开始\t" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("test()方法运行结束\t" + Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();
        //线程的isAlive()方法的功能是判断当前线程是否处于活动状态(就绪状态或者运行状态)
        //下面的循环会在两个线程都运行结束后 结束
        while(t1.isAlive() || t2.isAlive()){

        }
        System.out.println("程序运行结束");
    }
}

代码运行结果:
test()方法运行开始	Thread-0
test()方法运行结束	Thread-0
test()方法运行开始	Thread-1
test()方法运行结束	Thread-1
程序运行结束

 

注:多个thread对象在创建的时候,可以使用同一个Runnable对象作为初始参数,而且可以使用Synchronized将这个Runnable对象锁住,使多个thread对象在使用该Runnable对象的时候,达到并发安全。Synchronized可以直接修饰Runnable对象的run()方法。

延伸:使用idea进行线程调试的方法(3分钟):https://www.imooc.com/video/18484/0

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值