Java实现同步的几种方式

转自 http://fangjian0423.github.io/2016/04/18/java-synchronize-way/

Java提供了很多同步操作,比如synchronized关键字、wait/notifyAll、ReentrantLock、Condition、一些并发包下的工具类、Semaphore,ThreadLocal、AbstractQueuedSynchronizer等。

本文简单说明一下这几种方式的使用。

ReentrantLock可重入锁

ReentrantLock可重入锁是jdk内置的一个锁对象,可以用来实现同步,基本使用方法如下:


   
   
  1. public class ReentrantLockTest {
  2. private ReentrantLock lock = new ReentrantLock();
  3. public void execute() {
  4. lock. lock();
  5. try {
  6. System. out.println(Thread.currentThread().getName() + ” do something synchronize”);
  7. try {
  8. Thread.sleep( 5000l);
  9. } catch (InterruptedException e) {
  10. System.err.println(Thread.currentThread().getName() + ” interrupted”);
  11. Thread.currentThread().interrupt();
  12. }
  13. } finally {
  14. lock.unlock();
  15. }
  16. }
  17. public static void main(String[] args) {
  18. ReentrantLockTest reentrantLockTest = new ReentrantLockTest();
  19. Thread thread1 = new Thread( new Runnable() {
  20. @ Override
  21. public void run ( ) {
  22. reentrantLockTest.execute();
  23. }
  24. });
  25. Thread thread2 = new Thread( new Runnable() {
  26. @ Override
  27. public void run ( ) {
  28. reentrantLockTest.execute();
  29. }
  30. });
  31. thread1.start();
  32. thread2.start();
  33. }
  34. }

输出:


   
   
  1. Thread- 0 do something synchronize
  2. // 隔了5秒钟 输入下面
  3. Thread- 1 do something synchronize

这个例子表示同一时间段只能有1个线程执行execute方法。

可重入锁中可重入表示的意义在于对于同一个线程,可以继续调用加锁的方法,而不会被挂起。可重入锁内部维护一个计数器,对于同一个线程调用lock方法,计数器+1,调用unlock方法,计数器-1。

举个例子再次说明一下可重入的意思,在一个加锁方法execute中调用另外一个加锁方法anotherLock并不会被挂起,可以直接调用(调用execute方法时计数器+1,然后内部又调用了anotherLock方法,计数器+1,变成了2):


   
   
  1. public void execute() {
  2. lock. lock();
  3. try {
  4. System. out.println(Thread.currentThread().getName() + " do something synchronize");
  5. try {
  6. anotherLock();
  7. Thread.sleep( 5000l);
  8. } catch (InterruptedException e) {
  9. System.err.println(Thread.currentThread().getName() + " interrupted");
  10. Thread.currentThread().interrupt();
  11. }
  12. } finally {
  13. lock.unlock();
  14. }
  15. }
  16. public void anotherLock() {
  17. lock. lock();
  18. try {
  19. System. out.println(Thread.currentThread().getName() + " invoke anotherLock");
  20. } finally {
  21. lock.unlock();
  22. }
  23. }

输出:


   
   
  1. Thread-0 do something synchronize
  2. Thread -0 invoke anotherLock
  3. // 隔了 5秒钟 输入下面
  4. Thread -1 do something synchronize
  5. Thread -1 invoke anotherLock

synchronized关键字

synchronized关键跟ReentrantLock一样,也支持可重入锁。但是它是一个关键字,是一种语法级别的同步方式,称为内置锁:


   
   
  1. public class SynchronizedKeyWordTest {
  2. public synchronized void execute() {
  3. System.out.println(Thread.currentThread().getName() + " do something synchronize");
  4. try {
  5. anotherLock();
  6. Thread.sleep( 5000l);
  7. } catch (InterruptedException e) {
  8. System.err.println(Thread.currentThread().getName() + " interrupted");
  9. Thread.currentThread().interrupt();
  10. }
  11. }
  12. public synchronized void anotherLock() {
  13. System.out.println(Thread.currentThread().getName() + " invoke anotherLock");
  14. }
  15. public static void main(String[] args) {
  16. SynchronizedKeyWordTest reentrantLockTest = new SynchronizedKeyWordTest();
  17. Thread thread1 = new Thread( new Runnable() {
  18. @Override
  19. public void run() {
  20. reentrantLockTest.execute();
  21. }
  22. });
  23. Thread thread2 = new Thread( new Runnable() {
  24. @Override
  25. public void run() {
  26. reentrantLockTest.execute();
  27. }
  28. });
  29. thread1.start();
  30. thread2.start();
  31. }
  32. }

输出结果跟ReentrantLock一样,这个例子说明内置锁可以作用在方法上。它还可以作用到变量,静态方法上。

synchronized跟ReentrantLock相比,有几点局限性:

  1. 加锁的时候不能设置超时。ReentrantLock有提供tryLock方法,可以设置超时时间,如果超过了这个时间并且没有获取到锁,就会放弃,而synchronized却没有这种功能
  2. ReentrantLock可以使用多个Condition,而synchronized却只能有1个
  3. 不能中断一个试图获得锁的线程
  4. ReentrantLock可以选择公平锁和非公平锁
  5. ReentrantLock可以获得正在等待线程的个数,计数器等

Condition条件对象

条件对象的意义在于对于一个已经获取锁的线程,如果还需要等待其他条件才能继续执行的情况下,才会使用Condition条件对象。


   
   
  1. public class ConditionTest {
  2. public static void main(String[] args) {
  3. ReentrantLock lock = new ReentrantLock();
  4. Condition condition = lock.newCondition();
  5. Thread thread1 = new Thread( new Runnable() {
  6. @ Override
  7. public void run ( ) {
  8. lock. lock();
  9. try {
  10. System. out.println(Thread.currentThread().getName() + " run");
  11. System. out.println(Thread.currentThread().getName() + " wait for condition");
  12. try {
  13. condition. await();
  14. System. out.println(Thread.currentThread().getName() + " continue");
  15. } catch (InterruptedException e) {
  16. System.err.println(Thread.currentThread().getName() + " interrupted");
  17. Thread.currentThread().interrupt();
  18. }
  19. } finally {
  20. lock.unlock();
  21. }
  22. }
  23. });
  24. Thread thread2 = new Thread( new Runnable() {
  25. @ Override
  26. public void run ( ) {
  27. lock. lock();
  28. try {
  29. System. out.println(Thread.currentThread().getName() + " run");
  30. System. out.println(Thread.currentThread().getName() + " sleep 5 secs");
  31. try {
  32. Thread.sleep( 5000l);
  33. } catch (InterruptedException e) {
  34. System.err.println(Thread.currentThread().getName() + " interrupted");
  35. Thread.currentThread().interrupt();
  36. }
  37. condition.signalAll();
  38. } finally {
  39. lock.unlock();
  40. }
  41. }
  42. });
  43. thread1.start();
  44. thread2.start();
  45. }
  46. }

这个例子中thread1执行到condition.await()时,当前线程会被挂起,直到thread2调用了condition.signalAll()方法之后,thread1才会重新被激活执行。

这里需要注意的是thread1调用Condition的await方法之后,thread1线程释放锁,然后马上加入到Condition的等待队列,由于thread1释放了锁,thread2获得锁并执行,thread2执行signalAll方法之后,Condition中的等待队列thread1被取出并加入到AQS中,接下来thread2执行完毕之后释放锁,由于thread1已经在AQS的等待队列中,所以thread1被唤醒,继续执行。

wait/notifyAll 方式

wait/notifyAll方式跟ReentrantLock/Condition方式的原理是一样的。

Java中每个对象都拥有一个内置锁,在内置锁中调用wait,notify方法相当于调用锁的Condition条件对象的await和signalAll方法。

使用wait/notifyAll实现上面的那个Condition例子:


   
   
  1. public class WaitNotifyAllTest {
  2. public synchronized void doWait() {
  3. System. out.println(Thread.currentThread().getName() + " run");
  4. System. out.println(Thread.currentThread().getName() + " wait for condition");
  5. try {
  6. this.wait();
  7. System. out.println(Thread.currentThread().getName() + " continue");
  8. } catch (InterruptedException e) {
  9. System.err.println(Thread.currentThread().getName() + " interrupted");
  10. Thread.currentThread().interrupt();
  11. }
  12. }
  13. public synchronized void doNotify() {
  14. try {
  15. System. out.println(Thread.currentThread().getName() + " run");
  16. System. out.println(Thread.currentThread().getName() + " sleep 5 secs");
  17. Thread.sleep( 5000l);
  18. this.notifyAll();
  19. } catch (InterruptedException e) {
  20. System.err.println(Thread.currentThread().getName() + " interrupted");
  21. Thread.currentThread().interrupt();
  22. }
  23. }
  24. public static void main(String[] args) {
  25. WaitNotifyAllTest waitNotifyAllTest = new WaitNotifyAllTest();
  26. Thread thread1 = new Thread( new Runnable() {
  27. @ Override
  28. public void run ( ) {
  29. waitNotifyAllTest.doWait();
  30. }
  31. });
  32. Thread thread2 = new Thread( new Runnable() {
  33. @ Override
  34. public void run ( ) {
  35. waitNotifyAllTest.doNotify();
  36. }
  37. });
  38. thread1.start();
  39. thread2.start();
  40. }
  41. }

这里需要注意的是由于Condition是由锁创建的,所以调用wait/notifyAll方法的时候需要获得当前线程的锁,否则会发生IllegalMonitorStateException异常。

ThreadLocal

ThreadLocal是一种把变量放到线程本地的方式来实现线程同步的。

比如SimpleDateFormat不是一个线程安全的类,可以使用ThreadLocal实现同步。


   
   
  1. public class ThreadLocalTest {
  2. private static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {
  3. @ Override
  4. protected SimpleDateFormat initialValue ( ) {
  5. return new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
  6. }
  7. };
  8. public static void main(String[] args) {
  9. Thread thread1 = new Thread( new Runnable() {
  10. @ Override
  11. public void run ( ) {
  12. Date date = new Date();
  13. System. out.println(dateFormatThreadLocal. get().format(date));
  14. }
  15. });
  16. Thread thread2 = new Thread( new Runnable() {
  17. @ Override
  18. public void run ( ) {
  19. Date date = new Date();
  20. System. out.println(dateFormatThreadLocal. get().format(date));
  21. }
  22. });
  23. thread1.start();
  24. thread2.start();
  25. }
  26. }

Semaphore信号量

Semaphore信号量被用于控制特定资源在同一个时间被访问的个数。类似连接池的概念,保证资源可以被合理的使用。可以使用构造器初始化资源个数:


   
   
  1. public class SemaphoreTest {
  2. private static Semaphore semaphore = new Semaphore( 2);
  3. public static void main(String[] args) {
  4. for( int i = 0; i < 5; i ++) {
  5. new Thread( new Runnable() {
  6. @ Override
  7. public void run () {
  8. try {
  9. semaphore.acquire();
  10. System.out.println(Thread.currentThread().getName() + " " + new Date());
  11. Thread.sleep( 5000l);
  12. semaphore.release();
  13. } catch (InterruptedException e) {
  14. System.err.println(Thread.currentThread().getName() + " interrupted");
  15. }
  16. }
  17. }).start();
  18. }
  19. }
  20. }

输出:


   
   
  1. Thread- 1 Mon Apr 18 18 : 03 : 46 CST 2016
  2. Thread- 0 Mon Apr 18 18 : 03 : 46 CST 2016
  3. Thread- 3 Mon Apr 18 18 : 03 : 51 CST 2016
  4. Thread- 2 Mon Apr 18 18 : 03 : 51 CST 2016
  5. Thread- 4 Mon Apr 18 18 : 03 : 56 CST 2016

并发包下的工具类

一般情况下,我们不会使用wait/notifyAll或者ReentrantLock这种比较底层的类,而是使用并发包下提供的一些工具类。

CountDownLatch

CountDownLatch是一个计数器,它的构造方法中需要设置一个数值,用来设定计数的次数。每次调用countDown()方法之后,这个计数器都会减去1,CountDownLatch会一直阻塞着调用await()方法的线程,直到计数器的值变为0。


   
   
  1. public class CountDownLatchTest {
  2. public static void main(String[] args) {
  3. CountDownLatch countDownLatch = new CountDownLatch( 5);
  4. for( int i = 0; i < 5; i ++) {
  5. new Thread( new Runnable() {
  6. @ Override
  7. public void run () {
  8. System. out.println(Thread.currentThread().getName() + " " + new Date() + " run");
  9. try {
  10. Thread.sleep( 5000l);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. countDownLatch.countDown();
  15. }
  16. }).start();
  17. }
  18. try {
  19. countDownLatch. await();
  20. } catch (InterruptedException e) {
  21. e.printStackTrace();
  22. }
  23. System. out.println( "all thread over");
  24. }
  25. }

输出:


   
   
  1. Thread- 2 Mon Apr 18 18 : 18 : 30 CST 2016 run
  2. Thread- 3 Mon Apr 18 18 : 18 : 30 CST 2016 run
  3. Thread- 4 Mon Apr 18 18 : 18 : 30 CST 2016 run
  4. Thread- 0 Mon Apr 18 18 : 18 : 30 CST 2016 run
  5. Thread- 1 Mon Apr 18 18 : 18 : 30 CST 2016 run
  6. all thread over

CyclicBarrier

CyclicBarrier阻塞调用的线程,直到条件满足时,阻塞的线程同时被打开。

调用await()方法的时候,这个线程就会被阻塞,当调用await()的线程数量到达屏障数的时候,主线程就会取消所有被阻塞线程的状态。

在CyclicBarrier的构造方法中,还可以设置一个barrierAction。

在所有的屏障都到达之后,会启动一个线程来运行这里面的代码。


   
   
  1. public class CyclicBarrierTest {
  2. public static void main(String[] args) {
  3. Random random = new Random();
  4. CyclicBarrier cyclicBarrier = new CyclicBarrier( 5);
  5. for( int i = 0; i < 5; i ++) {
  6. new Thread( new Runnable() {
  7. @ Override
  8. public void run () {
  9. int secs = random.nextInt( 5);
  10. System. out.println(Thread.currentThread().getName() + " " + new Date() + " run, sleep " + secs + " secs");
  11. try {
  12. Thread.sleep(secs * 1000);
  13. cyclicBarrier. await();
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. } catch (BrokenBarrierException e) {
  17. e.printStackTrace();
  18. }
  19. System. out.println(Thread.currentThread().getName() + " " + new Date() + " runs over");
  20. }
  21. }).start();
  22. }
  23. }
  24. }

相比CountDownLatch,CyclicBarrier是可以被循环使用的,而且遇到线程中断等情况时,还可以利用reset()方法,重置计数器,从这些方面来说,CyclicBarrier会比CountDownLatch更加灵活一些。

AbstractQueuedSynchronizer

AQS是很多同步工具类的基础,比如ReentrentLock里的公平锁和非公平锁,Semaphore里的公平锁和非公平锁,CountDownLatch里的锁等他们的底层都是使用AbstractQueuedSynchronizer完成的。

基于AbstractQueuedSynchronizer自定义实现一个独占锁:


   
   
  1. public class MySynchronizer extends AbstractQueuedSynchronizer {
  2. @Override
  3. protected boolean tryAcquire(int arg) {
  4. if(compareAndSetState( 0, 1)) {
  5. setExclusiveOwnerThread(Thread.currentThread());
  6. return true;
  7. }
  8. return false;
  9. }
  10. @Override
  11. protected boolean tryRelease(int arg) {
  12. setState( 0);
  13. setExclusiveOwnerThread( null);
  14. return true;
  15. }
  16. public void lock() {
  17. acquire( 1);
  18. }
  19. public void unlock() {
  20. release( 1);
  21. }
  22. public static void main(String[] args) {
  23. MySynchronizer mySynchronizer = new MySynchronizer();
  24. Thread thread1 = new Thread( new Runnable() {
  25. @Override
  26. public void run() {
  27. mySynchronizer.lock();
  28. try {
  29. System.out.println(Thread.currentThread().getName() + " run");
  30. System.out.println(Thread.currentThread().getName() + " will sleep 5 secs");
  31. try {
  32. Thread.sleep( 5000l);
  33. System.out.println(Thread.currentThread().getName() + " continue");
  34. } catch (InterruptedException e) {
  35. System.err.println(Thread.currentThread().getName() + " interrupted");
  36. Thread.currentThread().interrupt();
  37. }
  38. } finally {
  39. mySynchronizer.unlock();
  40. }
  41. }
  42. });
  43. Thread thread2 = new Thread( new Runnable() {
  44. @Override
  45. public void run() {
  46. mySynchronizer.lock();
  47. try {
  48. System.out.println(Thread.currentThread().getName() + " run");
  49. } finally {
  50. mySynchronizer.unlock();
  51. }
  52. }
  53. });
  54. thread1.start();
  55. thread2.start();
  56. }
  57. }

MySynchronizer并没有实现可重入功能,只是简单的一个独占锁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值