多线程重点---synchronized用法

1.synchronized

  • 解决:原子性,内存可见性,指令重排序
  • 使用场景:一读一写,多写,
  • 缺点:重量
  • 本质上是加锁,针对某个对象加锁,只有一个线程能获取到该对象的锁,其他线程只能阻塞等待
  • 实际上就是把并发变成了串行,除去了抢占式执行带来的随机性

2.synchronize(关键字) 监视器锁(atm取钱)

  • 功能:保证操作的原子性,禁止指令重排序,保证内存可见性

3.2修饰一个方法

相当于加了LOCK,UNLOCK


  synchronized  public   void increase(){
        count++;

    }

4修饰一个代码块

   public void increase() {
        synchronized (this) {
            count++;
        }
    }
Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 50000; i++) {
                    synchronized(counter){
                        counter.increase();
                    }
                }
            }
        };

5嵌套加锁

  • synchronized内部进行了特殊处理,可重入锁。
  • 在这里插入图片描述
/**
 * User:yang
 */
class Counter {
    public static int count = 0;
//      public   void increase(){
//        count++;
//
//    }

    synchronized void increase() {
        count++;

    }

//    public void increase() {
//        synchronized (this) {
//            count++;
//        }
//    }
}

public class ThreadDemo12 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        Thread t1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 50000; i++) {
                    synchronized (counter) {
                        counter.increase();
                    }
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 50000; i++) {
                    synchronized (counter) {
                        counter.increase();
                    }
                }
            }
        };
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.count);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值