ThreadSafe-1

ThreadSafe-1-同步关键字和ReentrantLock

What is synchronized?

How to understand it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class ThreadSafeSample {
   public int sharedState;

   public void nonSafeAction() {
       System.err.println("非线程安全");
      while (sharedState < 100000) {
         int former = sharedState++;
         int latter = sharedState;
         if (former != latter - 1) {
            System.out.println("Observed data race, former is " + former + ", "
                  + "latter is " + latter);
         }
      }
   }


   public void safeActionWithSync()
    {
        //class为锁,或者当前的this为锁
        synchronized (ThreadSafeSample.class)
        {
            System.err.println("同步关键字");
            while (sharedState < 100000) {
                int former = sharedState++;
                int latter = sharedState;
                if (former != latter - 1) {
                    System.out.println("Observed data race, former is " + former + ", "
                            + "latter is " + latter);
                }
            }
        }
    }

   public static void main(String[] args) throws InterruptedException {
      ThreadSafeSample sample = new ThreadSafeSample();
      Thread threadA = new Thread() {
         public void run() {
            sample.nonSafeAction();
         }
      };
      Thread threadB = new Thread() {
         public void run() {
            sample.nonSafeAction();
         }
      };
      threadA.start();
      threadB.start();
      threadA.join();
      threadB.join();
      System.out.println("---------------------------------分割线");
        sample.sharedState=0;
      threadA =new Thread(()->{
          sample.safeActionWithSync();
        });
      threadB =new Thread(()->{
          sample.safeActionWithSync();
        });
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();
   }

Monitor

同步关键字的底层实现,在并发模型中一般翻译成管程;

ReentrantLock

Java 1.5中Doug Lea提出的JDK新实现的可重入锁,内部基于AQS,而AQS又基于CAS;

区别

两者的共同点是

  • 协调多线程对共享对象和共享变量的访问
  • 可重入,同一线程可以多次获得同一个锁
  • 都保证了可见性和互斥性,通过happens-before原则

不同点

  • ReentrantLock显示获得、释放锁,synchronized隐式获得释放锁
  • ReentrantLock可响应中断、可轮回,synchronized是不可以响应中断的,为处理锁的不可用性提供了更高的灵活性
  • ReentrantLockAPI级别的,synchronizedJVM级别的,换句话说是直接操作管程的;
  • ReentrantLock可以实现公平锁,synchronized是非公平的;
  • ReentrantLock通过Condition可以绑定多个条件
  • 底层实现不一样, synchronized是同步阻塞,使用的是悲观并发策略,lock是同步非阻塞,采用的是乐观并发策略这部分对于乐观和悲观的理解我觉得是存在歧义的;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值