1、概念理解:

2、同步的解决方案:

1).基于代码

synchronized 关键字

  修饰普通方法:作用于当前实例加锁,进入同步代码前要获得当前实例的锁。

  修饰静态方法:作用于当前类对象加锁,进入同步代码前要获得当前类对象的锁。

  修饰代码块:指定加锁对象,对给定对象加锁,进入同步代码块前要获得给定对象的锁。

code1

  1. package com.thread;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5.  
  6. /**
  7. * 同步方法
  8. * @author Administrator
  9. *
  10. */
  11. public class SynchronizedMethod implements Runnable{
  12.  
  13. //静态共享变量 i
  14. static int i = 0;
  15.  
  16. /**
  17. * 自增
  18. */
  19. public synchronized void increase(){
  20. i++;
  21. }
  22.  
  23. @Override
  24. public void run() {
  25. for (int j = 0; j < 100; j++) {
  26. increase();
  27. }
  28. }
  29.  
  30. public static void main(String[] args) throws InterruptedException {
  31. SynchronizedMethod instance = new SynchronizedMethod();
  32. ExecutorService executorService = Executors.newFixedThreadPool(2);
  33. for (int i = 0; i < 3; i++) {
  34. //同一实例,线程共享静态变量i
  35. // executorService.execute(instance);
  36. //不同实例,线程单独享有变量i,达不到同步目的
  37. executorService.execute(new SynchronizedMethod());
  38. /**
  39. * 由于线程执行时间过短,在不同实例下,可能会得到类似于同步的结果。
  40. */
  41. Thread.sleep(100);
  42. }
  43.  
  44. executorService.shutdown();
  45.  
  46. System.out.println(i); //
  47.  
  48. }
  49. }

code2

  1. package com.thread;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5.  
  6. /**
  7. * 同步代码块
  8. * @author Administrator
  9. *
  10. */
  11. public class SynchronizedCodeBlock implements Runnable{
  12.  
  13. //静态共享变量 i
  14. static int i = 0;
  15.  
  16. @Override
  17. public void run() {
  18. //同步进来的对象
  19. synchronized(this){ //SynchronizedCodeBlock.class
  20. for (int j = 0; j < 100; j++) {
  21. i++;
  22. }
  23. }
  24. }
  25.  
  26. public static void main(String[] args) throws InterruptedException {
  27. SynchronizedCodeBlock instance = new SynchronizedCodeBlock();
  28. ExecutorService executorService = Executors.newFixedThreadPool(2);
  29. for (int i = 0; i < 3; i++) {
  30. // executorService.execute(instance);
  31. executorService.execute(new SynchronizedCodeBlock());
  32. Thread.sleep(10);
  33. }
  34.  
  35. executorService.shutdown();
  36.  
  37. System.out.println(i); //
  38.  
  39. }
  40. }

wait与notify运用

wait():使一个线程处于等待状态,并且释放所持有的对象的lock。

sleep():使一个正在运行的线程处于睡眠状态,是一个静态方法,调用此方法要捕捉InterruptedException异常。

notify():唤醒一个处于等待状态的线程,注意的是在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,而是由JVM确定唤醒哪个线程,而且不是按优先级。

notifyAll():唤醒所有处入等待状态的线程,注意并不是给所有唤醒线程一个对象的锁,而是让它们竞争。

code3

  1. package com.test;
  2.  
  3. /**
  4. * 多线程实现 生产者-消费者模式
  5. * 关键点:wait和notifyAll或者notify时机的运用,确保先生产后消费
  6. * @author Administrator
  7. *
  8. */
  9. public class Test
  10. {
  11. private static Integer count = 0; //数据仓库计数
  12. private final Integer FULL = 5; //数据仓库最大存储量
  13. private static String lock = "lock"; //锁标识
  14.  
  15. public static void main(String[] args)
  16. {
  17. Test t = new Test();
  18. new Thread(t.new Producer()).start();
  19. new Thread(t.new Consumer()).start();
  20. new Thread(t.new Producer()).start();
  21. new Thread(t.new Consumer()).start();
  22. }
  23.  
  24. //生产者
  25. class Producer implements Runnable
  26. {
  27. @Override
  28. public void run()
  29. {
  30. for (int i = 0; i < 5; i++)
  31. {
  32. try {
  33. Thread.sleep(1000);
  34. } catch (InterruptedException e1) {
  35. e1.printStackTrace();
  36. }
  37. synchronized (lock)
  38. {
  39. while (count == FULL)
  40. {
  41. try {
  42. lock.wait();
  43. } catch (InterruptedException e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. count++;
  48. System.out.println(Thread.currentThread().getName() + "produce:: " + count);
  49. //唤醒lock锁上的所有线程
  50. lock.notifyAll();
  51. }
  52. }
  53. }
  54. }
  55.  
  56. //消费者
  57. class Consumer implements Runnable
  58. {
  59. @Override
  60. public void run()
  61. {
  62. for (int i = 0; i < 5; i++)
  63. {
  64. try {
  65. Thread.sleep(1000);
  66. } catch (InterruptedException e1) {
  67. e1.printStackTrace();
  68. }
  69. synchronized (lock)
  70. {
  71. //如果首次消费者竞争得到锁,进入后等待
  72. while (count == 0)
  73. {
  74. try {
  75. lock.wait();
  76. } catch (InterruptedException e) {
  77. e.printStackTrace();
  78. }
  79. }
  80. count--;
  81. System.out.println(Thread.currentThread().getName()+ "consume:: " + count);
  82. lock.notifyAll();
  83. }
  84. }
  85. }
  86. }
  87. }

volatile实现线程同步

原理:volatile保证不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,新值对其他线程来说是立即可见的,并且禁止进行指令重排序。

注意:volatile不保证原子性,凡是不是原子性的操作,都不能保证可见性,也即不能保证同步

应用:

  1)对变量的写操作不依赖于当前值 类似 i++、i=j 等操作 不能对 i 用volatile。解决办法:类似操作增加 synchronized、Lock、AtomicInteger 保证原子性。

  2)该变量没有包含在具有其他变量的不变式中

  常用在多线程状态标志 flag、

ReentrantLock重入锁

重入锁:外层函数获取锁后,内层函数依然有获取该锁的代码,则重入锁无需再次获取锁,即可进入内层代码

code1

  1. package com.lock;
  2.  
  3. import java.util.concurrent.ExecutorService;
  4. import java.util.concurrent.Executors;
  5. import java.util.concurrent.locks.ReentrantLock;
  6.  
  7. /**
  8. * 重入锁
  9. * 外层函数获取锁后,内层函数依然有获取该锁的代码,则重入锁无需再次获取锁,即可进入内层代码
  10. * ReentrantLock 和synchronized 都是 可重入锁
  11. * @author Administrator
  12. *
  13. */
  14. public class ReentranLockTest implements Runnable{
  15.  
  16. public static ReentrantLock lock = new ReentrantLock();
  17. public static int i = 0;
  18.  
  19. @Override
  20. public void run() {
  21. for (int j = 0; j < 10; j++) {
  22. lock.lock(); //加锁
  23. try {
  24. i++;
  25. } finally {
  26. lock.unlock(); //释放锁
  27. }
  28. }
  29. }
  30.  
  31. public static void main(String[] args) throws InterruptedException {
  32. ReentranLockTest test = new ReentranLockTest();
  33.  
  34. ExecutorService executorService = Executors.newFixedThreadPool(2);
  35. for (int i = 0; i < 2; i++) {
  36. executorService.execute(test);
  37. Thread.sleep(1000);
  38. }
  39. executorService.shutdown();
  40. System.out.println(i);
  41.  
  42. }
  43. }

code2

  1. package com.lock;
  2.  
  3. import java.util.concurrent.locks.Lock;
  4. import java.util.concurrent.locks.ReentrantLock;
  5.  
  6. /**
  7. * 可中断的重入锁
  8. * 条件中断等待
  9. * @author Administrator
  10. *
  11. */
  12. public class InterruptiblyLockTest {
  13.  
  14. public static Lock lock = new ReentrantLock();
  15.  
  16. public void function(){
  17. String tName = Thread.currentThread().getName();
  18. try {
  19. System.out.println(tName + "-开始获取锁......");
  20. lock.lockInterruptibly();
  21. System.out.println("获取到锁了......");
  22. Thread.sleep(10000);
  23. System.out.println("睡眠10秒后,开始干活......");
  24. for (int i = 0; i < 5; i++) {
  25. System.out.println(tName + ":" + i);
  26. }
  27. System.out.println("活干完了......");
  28. } catch (Exception e) {
  29. System.out.println(tName + "-我好像被人中断了!");
  30. e.printStackTrace();
  31. }finally {
  32. lock.unlock();
  33. System.out.println(tName + "-释放了锁");
  34. }
  35. }
  36.  
  37. public static void main(String[] args) throws InterruptedException {
  38. InterruptiblyLockTest test = new InterruptiblyLockTest();
  39. //定义两个线程
  40. Thread t0 = new Thread() {
  41. public void run() {
  42. test.function();
  43. }
  44. };
  45.  
  46. Thread t1 = new Thread() {
  47. public void run() {
  48. test.function();
  49. }
  50. };
  51.  
  52. String tName = Thread.currentThread().getName();
  53. System.out.println(tName + "-启动t0");
  54. t0.start();
  55. System.out.println(tName + "-等5秒,再启动t1");
  56. Thread.sleep(5000);
  57. System.out.println(tName + "-启动t1");
  58. t1.start();
  59. //t0先占据了锁还在睡眠
  60. System.out.println(tName + "-不等了,把t1中断掉!");
  61. t1.interrupt(); //中断:只能中断处于等待锁的线程,不能中断已经获取锁的线程
  62. }
  63. }

code3

  1. package com.lock;
  2.  
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import java.util.concurrent.TimeUnit;
  6. import java.util.concurrent.locks.ReentrantLock;
  7.  
  8. /**
  9. * 尝试型锁
  10. * 拒绝阻塞
  11. * @author Administrator
  12. *
  13. */
  14. public class TryLockTest {
  15.  
  16. public ReentrantLock lock = new ReentrantLock();
  17.  
  18. /**
  19. * tryLock
  20. * 当前资源没有被占用,则tryLock获取锁
  21. * 当前资源被当前锁占用,则tryLock返回true
  22. * 当前资源被其他线程占用,则tryLock返回false
  23. * @throws InterruptedException
  24. */
  25. public void tryLockFunction() throws InterruptedException{
  26. String tName = Thread.currentThread().getName();
  27. if(lock.tryLock()){
  28. try {
  29. System.out.println(tName + "-获取到锁了");
  30. Thread.sleep(3000);
  31. System.out.println(tName + "工作了3秒钟......");
  32. } finally {
  33. lock.unlock();
  34. System.out.println(tName + "-释放锁");
  35. }
  36. }else{
  37. System.out.println(tName + "-无法获取到锁");
  38. }
  39. }
  40.  
  41. /**
  42. * tryLock(long timeout, TimeUnit unit)
  43. * timeout时间内尝试请求锁,请求到了则返回true,可被中断
  44. *
  45. * @throws InterruptedException
  46. */
  47. public void tryLockInterruptFunction() throws InterruptedException{
  48. String tName = Thread.currentThread().getName();
  49. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd:hh:mm:ss");
  50. System.out.println(tName + "-开始尝试获取锁,当前时间:"+format.format(new Date()));
  51. if(lock.tryLock(3,TimeUnit.SECONDS)){
  52. try {
  53. System.out.println(tName + "-获取到锁了");
  54. Thread.sleep(5000);
  55. System.out.println(tName + "工作了3秒钟......");
  56. } finally {
  57. lock.unlock();
  58. System.out.println(tName + "-释放锁");
  59. }
  60. }else{
  61. System.out.println(tName + "-无法获取到锁");
  62. System.out.println(tName + "-结束尝试获取锁,当前时间:"+format.format(new Date()));
  63. }
  64. }
  65.  
  66. public static void main(String[] args) {
  67. TryLockTest test = new TryLockTest();
  68. new Thread("Lock-Thread1") {
  69. public void run() {
  70. try {
  71. test.tryLockFunction();
  72. } catch (InterruptedException e) {
  73. e.printStackTrace();
  74. }
  75. }
  76. }.start();
  77. new Thread("Lock-Thread2") {
  78. public void run() {
  79. try {
  80. test.tryLockFunction();
  81. } catch (InterruptedException e) {
  82. e.printStackTrace();
  83. }
  84. }
  85. }.start();
  86.  
  87. //Lock-Thread1-获取到锁了
  88. //Lock-Thread2-无法获取到锁
  89. //Lock-Thread1工作了3秒钟......
  90. //Lock-Thread1-释放锁
  91.  
  92. new Thread("LockInterrupt-Thread1") {
  93. public void run() {
  94. try {
  95. test.tryLockInterruptFunction();
  96. } catch (InterruptedException e) {
  97. e.printStackTrace();
  98. }
  99. }
  100. }.start();
  101. new Thread("LockInterrupt-Thread2") {
  102. public void run() {
  103. try {
  104. test.tryLockInterruptFunction();
  105. } catch (InterruptedException e) {
  106. e.printStackTrace();
  107. }
  108. }
  109. }.start();
  110.  
  111. //LockInterrupt-Thread2-开始尝试获取锁,当前时间:2019-01-17:05:12:32
  112. //LockInterrupt-Thread1-开始尝试获取锁,当前时间:2019-01-17:05:12:32
  113. //LockInterrupt-Thread2-获取到锁了
  114. //LockInterrupt-Thread1-无法获取到锁
  115. //LockInterrupt-Thread1-结束尝试获取锁,当前时间:2019-01-17:05:12:35
  116. //LockInterrupt-Thread2工作了3秒钟......
  117. //LockInterrupt-Thread2-释放锁
  118.  
  119. }
  120. }

code4

  1. package com.lock;
  2.  
  3. import java.util.concurrent.locks.ReentrantLock;
  4.  
  5. /**
  6. * 公平锁
  7. * 按时间先后获取锁
  8. * @author Administrator
  9. *
  10. */
  11. public class FairLockTest {
  12. //创建一个公平锁
  13. public static ReentrantLock lock = new ReentrantLock(true);
  14.  
  15. public void fairLockFunction(){
  16. while(true){
  17. try {
  18. lock.lock();
  19. System.out.println(Thread.currentThread().getName()+"获取到锁......");
  20. } finally {
  21. lock.unlock();
  22. }
  23. }
  24. }
  25.  
  26. public static void main(String[] args) {
  27. FairLockTest test = new FairLockTest();
  28. Thread t1 = new Thread("线程1") {
  29. public void run() {
  30. test.fairLockFunction();
  31. }
  32. };
  33. Thread t2 = new Thread("线程2") {
  34. public void run() {
  35. test.fairLockFunction();
  36. }
  37. };
  38. t1.start();
  39. t2.start();
  40. }
  41.  
  42. //线程1获取到锁......
  43. //线程2获取到锁......
  44. //线程1获取到锁......
  45. //线程2获取到锁......
  46. //线程1获取到锁......
  47. //线程2获取到锁......
  48. //线程1获取到锁......
  49. //线程2获取到锁......
  50. }

ThreadLocal创建线程间变量副本

参考博客:聊一聊Spring中的线程安全性

final实现volatile可见性

  通过final不可变性的特点,替代volatile的可见性。

参考博客:

https://blog.csdn.net/javazejian/article/details/72828483

https://www.cnblogs.com/duanxz/p/3709608.html?utm_source=tuicool&utm_medium=referral

http://www.cnblogs.com/duanxz/p/5066726.html

2).基于数据库

Java高并发之同步异步的更多相关文章

  1. Java高并发之锁优化

    本文主要讲并行优化的几种方式, 其结构如下: 锁优化 减少锁的持有时间 例如避免给整个方法加锁 public synchronized void syncMethod(){ othercode1(); ...

  2. java高并发之线程池

    Java高并发之线程池详解   线程池优势 在业务场景中, 如果一个对象创建销毁开销比较大, 那么此时建议池化对象进行管理. 例如线程, jdbc连接等等, 在高并发场景中, 如果可以复用之前销毁的对 ...

  3. java高并发之锁的使用以及原理浅析

    锁像synchronized同步块一样,是一种线程同步机制.让自Java 5开始,java.util.concurrent.locks包提供了另一种方式实现线程同步机制——Lock.那么问题来了既然都 ...

  4. Java高并发之线程基本操作

    结合上一篇同步异步,这篇理解线程操作. 1.新建线程.不止thread和runnable,Callable和Future了解一下 package com.thread; import java.tex ...

  5. Java高并发之设计模式

    本文主要讲解几种常见并行模式, 具体目录结构如下图. 单例 单例是最常见的一种设计模式, 一般用于全局对象管理, 比如xml配置读写之类的. 一般分为懒汉式, 饿汉式. 懒汉式: 方法上加synchr ...

  6. 1.6 JAVA高并发之线程池

    一.JAVA高级并发 1.5JDK之后引入高级并发特性,大多数的特性在java.util.concurrent 包中,是专门用于多线程发编程的,充分利用了现代多处理器和多核心系统的功能以编写大规模并发 ...

  7. Java 高并发之魂

    前置知识 了解Java基本语法 了解多线程基本知识 知识介绍 Synchronized简介:作用.地位.不控制并发的后果 两种用法:对象锁和类锁 多线程访问同步方法的7种情况:是否是static.Sy ...

  8. Java高并发之从零到放弃

    前言 本篇主要讲解如何去优化锁机制或者克服多线程因为锁可导致性能下降的问题 ThreadLocal线程变量 有这样一个场景,前面是一大桶水,10个人去喝水,为了保证线程安全,我们要在杯子上加锁导致大家 ...

  9. Java高并发之无锁与Atomic源码分析

    目录 CAS原理 AtomicInteger Unsafe AtomicReference AtomicStampedReference AtomicIntegerArray AtomicIntege ...

随机推荐

  1. android finish和system.exit(0)的区别

    finish是Activity的类,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理:当调用System.exit(0)时,杀死了整个 ...

  2. MVC之ViewData.Model

    在MVC中前台Razor视图呈现数据的方式不止一种.举个简单的Demo,我们要把用户信息呈现给人民. 一.ViewData.Model的使用,先简单写一下Razor @model   User---- ...

  3. 修复kindEditor点击加粗, 内容焦点跳动的问题

    大概1560~1569行 pos : function() { var self = this, node = self[0], x = 0, y = 0; if (node) { if (node. ...

  4. CSS Grid 布局学习笔记

    CSS Grid 布局学习笔记 好久没有写博客了, MDN 上关于 Grid 布局的知识比较零散, 正好根据我这几个月的实践对 CSS Grid 布局做一个总结, 以备查阅. 1. 基础用法 Grid ...

  5. 使用js来执行全屏

    当用户按下F11事件,浏览器为触发自身全屏功能,这个过程我们一般是不可控制的,即使是监听了F11的键盘事件,退出全屏的时候,我们也捕捉不到退出全屏触发的事件.所以,我们就用程序自己去实现F11的功能, ...

  6. android libs库中的armeabi-v7a,armeabi和x86

    以下内容转载于:http://blog.csdn.net/liumou111/article/details/52949156 1.区别: 这三者都表示的是CPU类型,早期的Android系统几乎只支 ...

  7. selenium中Alter等弹出对话框的处理

    昨天使用selenium做自动化测试,发现部分页面会弹出alert对话框,找了写资料,大概的意思就是要给弹出的对话框做出相应,不然,后续的处理会失败. _driver.SwitchTo().Alert ...

  8. 我的ORM框架

    任何系统的基础,都可以算是各种数据的增删改查(CRUD).最早操作数据是直接在代码里写SQL语句,后来出现了各种ORM框架.C#下的ORM框架有很多,如微软自己的Entity Framework.第三 ...

  9. Eclipse下JRebel的安装和基本使用

    JRebel有什么用? 做Java Web开发,一个很头疼的事情是,修改了一个类以后,Tomcat必须重新启动. 工程规模小还好说,如果规模大了,重启一次动不动就是一分多钟.那么频繁重启就会导致大量的 ...

  10. Vue.js-创建Vue项目(Vue项目初始化)并不是用Webstrom创建,只是用Webstrom打开

    我犯的错误:作为vue小白,并不知道还要单独去创建初始的vue项目,于是自己在webstrom中建了一个Empty Project, 在其中新增了一个js文件,就开始import Vue from “ ...