1.并发编程三要素
- 原子性:一个或多个操作要么全部成功,要么全部失败。
- 可见性:A线程对主内存的值进行修改并写回主内存后B线程能否立马就知道。
- 有序性:是否会禁止指令重排,比如volatile会禁止指令重排,那么volatile就可以保证有序性,即按代码编写的顺序执行。
2.i++
1.没有任何附加操作的i++
```java public class Test1 { public static void main(String[] args) {
} } class MyAdd{ public int num=0; public void add(){MyAdd myAdd=new MyAdd();for(int i=0;i<10;i++){new Thread(()->{for(int j=0;j<10000;j++){myAdd.add();}}).start();}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(myAdd.num);
} } 1.我们希望输出的num时1010000,但是每次输出的值都不一样,一般都是小于1010000; 2.编写代码的时候注意两点: 1.i和j的上界要设置大一点,否则很难重现i++的问题; 2.主线程需要等待其他线程执行完再打印出num值,不等待的情况下值是没有意义的。num++;
<a name="YXtoH"></a>## 2.加了synchronized的i++```javapublic class Test1 {public static void main(String[] args) {MyAdd myAdd=new MyAdd();for(int i=0;i<10;i++){new Thread(()->{for(int j=0;j<10000;j++){myAdd.add();}}).start();}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(myAdd.num);}}class MyAdd{public int num=0;public synchronized void add(){num++;}}1.在add方法上加synchronized就可以解决多线程i++的问题2.此时最后num的值都是100,000.
3.使用Reentrantlock的i++
public class Test1 {public static void main(String[] args) {MyAdd myAdd=new MyAdd();for(int i=0;i<10;i++){new Thread(()->{for(int j=0;j<10000;j++){myAdd.add();}}).start();}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(myAdd.num);}}class MyAdd{public int num=0;Lock lock=new ReentrantLock();public void add(){lock.lock();//lock()必须在后面跟try代码块try {num++;} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();//unlock()必须在finally的第一行}}}1.先创建一个Lock类型的变量;2.然后调用该变量的lock()方法,该方法后必须紧跟try-catch-finally方法;3.该变量的unlock()方法必须在finally的第一行。4.此时最后num的值都是100,000.
4.使用原子类的i++
public class Test1 {public static void main(String[] args) {MyAdd myAdd=new MyAdd();AtomicInteger atomicInteger=new AtomicInteger(0);for(int i=0;i<10;i++){new Thread(()->{for(int j=0;j<10000;j++){atomicInteger.getAndIncrement();}}).start();}try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(atomicInteger);}}1.创建AtomicInteger变量,初始值设置为02.直接在线程执行体中调用该变量的getAndIncrement()方法即可3.此时最后atomicInteger的值都是100,000.
3.进程调度和线程调度
进程调度:

线程调度:

4.乐/悲观,(非)公平,(可)重入,自旋,共享,互斥锁



- 锁的是什么,要么锁一个方法,要么锁一个代码块。
- 偏向锁,轻量级锁,重量级锁都是JVM层面对锁的优化,即提高锁的获取和释放效率
5.死锁演示和解决
1.死锁代码演示
public class Test1 {public static void main(String[] args) {String s1=new String("1");String s2=new String("1");new Thread(()->{synchronized (s1){System.out.println(Thread.currentThread().getName()+"已经拿到锁1了");try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}synchronized (s2){System.out.println(Thread.currentThread().getName()+"已经拿到锁2了");}}},"A线程").start();new Thread(()->{synchronized (s2){System.out.println(Thread.currentThread().getName()+"已经拿到锁2了");try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}synchronized (s1){System.out.println(Thread.currentThread().getName()+"已经拿到锁1了");}}},"B线程").start();System.out.println("主线程运行结束!");}}A线程已经拿到锁1了主线程运行结束!B线程已经拿到锁2了1.主线程不是守护线程,而是普通线程;2.此时A线程和B线程由于死锁所以两个都进入阻塞状态,无法正常结束。
2.死锁四个必要条件

3.死锁解决方法
public class Test1 {public static void main(String[] args) {String s1=new String("1");String s2=new String("1");new Thread(()->{synchronized (s1){System.out.println(Thread.currentThread().getName()+"已经拿到锁1了");try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}synchronized (s2){System.out.println(Thread.currentThread().getName()+"已经拿到锁2了");}},"A线程").start();new Thread(()->{synchronized (s2){System.out.println(Thread.currentThread().getName()+"已经拿到锁2了");try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}synchronized (s1){System.out.println(Thread.currentThread().getName()+"已经拿到锁1了");}},"B线程").start();System.out.println("主线程运行结束!");}}A线程已经拿到锁1了主线程运行结束!B线程已经拿到锁2了B线程已经拿到锁1了A线程已经拿到锁2了只要破坏四个必要条件中的至少一个,就可以解决死锁比如这里就是破坏请求与保持条件。
6.(不)可重入锁
1.不可重入锁(也会导致死锁)
public class Test1 {public static UnreentrantLock lock = new UnreentrantLock();public static void main(String[] args) throws InterruptedException {Test1.methodA();}public static void methodA() throws InterruptedException {lock.lock();try {System.out.println("MethodA加锁成功");methodB();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}System.out.println("MethodA解锁成功");}public static void methodB() throws InterruptedException {lock.lock();try {System.out.println("MethodB加锁成功");} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}System.out.println("MethodB解锁成功");}}class UnreentrantLock{public boolean isLocked=false;public synchronized void lock() throws InterruptedException {while(isLocked){System.out.println(Thread.currentThread().getName()+"无法获取锁");wait();}isLocked=true;}public synchronized void unlock() {isLocked=false;notify();}}运行输出:MethodA加锁成功main无法获取锁然后程序一直阻塞首先可重入锁和不可重入锁是针对同一个线程来说的;即对同一线程而言,先成功加了第一把锁,之后又加第二把锁,如果能成功则该锁就是可重入锁;当第一次获取Unreentrantlock这把锁之后,就会把isLocked置为true,之后再想获取这把锁时都会被阻塞在while循环中的wait方法处。注意点:1.我一开始写lock的时候while内部加了wait(),然后while外面就立马加了notify(),这个是没有必要的,因为这不是生成者消费者模式,不需要去争抢锁。2.为了跟真实的JUC包中的ReentrantLock的lock方法一致,我也把lock.lock()方法放在了try外面,此时就需要抛出异常,放在try立马是不需要抛出异常的,该异常是wait()方法触发的。3.我们之前在使用wait和notify的时候都是在多线程的生产者消费者中实践的,生产方法和消费方法中都会使用wait和notify方法,因为生产方法和消费方法是同级的。而这里是单线程。可重入锁和不可重入锁是针对同一个线程来说的。
2.可重入锁
public class Test1 {public static UnreentrantLock lock = new UnreentrantLock();public static void main(String[] args) throws InterruptedException {Test1.methodA();}public static void methodA() throws InterruptedException {lock.lock();try {System.out.println("MethodA加锁成功");methodB();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}System.out.println("MethodA解锁成功");}public static void methodB() throws InterruptedException {lock.lock();try {System.out.println("MethodB加锁成功");} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}System.out.println("MethodB解锁成功");}}class UnreentrantLock{public boolean isLocked=false;public Thread lockOwner=null;public int lockCount=0;public synchronized void lock() throws InterruptedException {Thread thread=Thread.currentThread();while(isLocked && lockOwner!=thread){System.out.println(Thread.currentThread().getName()+"无法获取锁");System.out.println("当前锁状态:isLocked:"+isLocked);System.out.println("当前count数量:lockCount:"+lockCount);wait();}isLocked=true;lockOwner=thread;lockCount++;}public synchronized void unlock() {Thread thread=Thread.currentThread();if(lockOwner==thread){lockCount--;if(lockCount==0){lockOwner=null;isLocked=false;notify();}}}}输出结果:MethodA加锁成功MethodB加锁成功MethodB解锁成功MethodA解锁成功程序执行结束跟不可重入锁的主要区别就是在lock方法的while判断中多加了一个thread!=lockOwner这表明只有当锁被占用,而且当前线程等于占用锁的线程时才会阻塞,其言外之意就是如果申请锁的线程就是占用锁的线程,则程序不会阻塞,会照常进行,这就是可重入。我感觉对于单线程来说,这里的unlock没有体现出它的作用,即如果我把unlock都注释掉,也不影响程序的效果。但是实际中肯定是多线程,如果没有unlock那么其他的线程就没法加锁。注意阻塞是while中的wait导致的阻塞,而不是while循环。
7.Synchronized底层
1.字节码层面
- 我们知道Synchronized可以加在普通方法,静态方法,代码块上
- 其实可以分成方法和代码块两个方式
- 我们通过字节码文件可以看出两者实现同步的不同之处




2.对象的三部分组成


3.Synchronized优化
为什么要优化?
因为原始的synchronized在线程无法申请到锁的时候就会让该线程进入阻塞状态,
则这涉及到操作系统内核模式和用户模式的切换(线程调度),代价比较高,
所以优化的核心是拒绝走来就阻塞。实在不行才阻塞。
8.CAS
1.是什么


2.cas存在的问题


9.可重入读写锁(ReentrantReadWriteLock)
10.阻塞队列
1.手写阻塞队列
public class test {public static void main(String[] args) {BlockingQ blockingQ=new BlockingQ(10);for(int i=0;i<10;i++){//1.lambda表达式中不能直接使用for循环中的iint finalI = i;new Thread(()->{//2.生成者消费者最好使用while(true),否则当生产者和消费者的线程的数目不一致时会出错while(true){try {blockingQ.enqueue(String.valueOf(finalI));System.out.println("队列当前元素个数:"+blockingQ.queque.size());} catch (InterruptedException e) {e.printStackTrace();}}}).start();}for(int i=0;i<20;i++){new Thread(()->{while(true){try {blockingQ.dequeue();System.out.println("队列当前元素个数:"+blockingQ.queque.size());} catch (InterruptedException e) {e.printStackTrace();}}}).start();}}}class BlockingQ{//3.如果使用的是List引用,则无法使用LinkedList特有的removeLast方法public LinkedList<Object> queque=new LinkedList<>();public int limit;public BlockingQ(int limit){this.limit=limit;}public synchronized void enqueue(Object object ) throws InterruptedException {while(this.queque.size()==limit){System.out.println("队列满了,没法继续添加了");wait();}notifyAll();this.queque.add(object);}public synchronized Object dequeue() throws InterruptedException {while(this.queque.size()==0){System.out.println("队列空了,没法继续获取了");wait();}notifyAll();return this.queque.removeLast();}}

讨论情况(在没有while(true)的情况下)
当我们把while(true)去掉,
并且改变生成者线程和消费者线程的相对数目时,
并且在等待一定时间之后在主线程中打印阻塞队列中的元素个数。
1.生成者10,消费者20
public static void main(String[] args) throws InterruptedException {BlockingQ blockingQ=new BlockingQ(10);for(int i=0;i<10;i++){int finalI = i;new Thread(()->{try {blockingQ.enqueue(String.valueOf(finalI));System.out.println("队列当前元素个数:"+blockingQ.queque.size());} catch (InterruptedException e) {e.printStackTrace();}}).start();}for(int i=0;i<20;i++){new Thread(()->{try {blockingQ.dequeue();System.out.println("队列当前元素个数:"+blockingQ.queque.size());} catch (InterruptedException e) {e.printStackTrace();}}).start();}Thread.sleep(2000);System.out.println(blockingQ.queque.size());}
分析:
由于消费者数目大于生成者,所以最后元素个数为0,
并且程序会阻塞在消费者线程中
2.生成者20,消费者20
分析:
程序正常结束,最后元素个数为0
3.生成者25,消费者20
分析:
程序正常结束,最后元素个数为5
4.生成者30,消费者20
分析:
程序正常结束,最后元素个数为10
5.生产者31,消费者20
分析:
由于31-20=11>阻塞队列的容量,
所以程序会阻塞在生成者线程中。
最后的元素个数为10。
2.直接用包(把我们自定义的阻塞队列换成java自带的就差不多)
public class BlockingQueueTest {public static void main(String[] args) {final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3); //缓冲区允许放3个数据for(int i = 0; i < 2; i ++) {new Thread() { //开启两个线程不停的往缓冲区存数据@Overridepublic void run() {while(true) {try {Thread.sleep((long) (Math.random()*1000));System.out.println(Thread.currentThread().getName() + "准备放数据"+ (queue.size() == 3?"..队列已满,正在等待":"..."));queue.put(1);System.out.println(Thread.currentThread().getName() + "存入数据,"+ "队列目前有" + queue.size() + "个数据");} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();}new Thread() { //开启一个线程不停的从缓冲区取数据@Overridepublic void run() {while(true) {try {Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + "准备取数据"+ (queue.size() == 0?"..队列已空,正在等待":"..."));queue.take();System.out.println(Thread.currentThread().getName() + "取出数据,"+ "队列目前有" + queue.size() + "个数据");} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}.start();}}
3.常见的阻塞队列

11.多线程最佳实践

12.Executors线程池
public static ExecutorService newSingleThreadExecutor() {return new FinalizableDelegatedExecutorService(new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));}由于ThreadPoolExecutor中的阻塞队列是LinkedBlockingQueue,而这个队列的容量是Integer.MAX_VALUE所以容易造成OOM
public static ExecutorService newFixedThreadPool(int nThreads) {return new ThreadPoolExecutor(nThreads, nThreads,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());}由于ThreadPoolExecutor中的阻塞队列是LinkedBlockingQueue,而这个队列的容量是Integer.MAX_VALUE所以容易造成OOM
public static ExecutorService newCachedThreadPool() {return new ThreadPoolExecutor(0, Integer.MAX_VALUE,60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());}由于ThreadPoolExecutor中的最大线程数是Integer.MAX_VALUE,所以容易造成OOM
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {return new ScheduledThreadPoolExecutor(corePoolSize);}public ScheduledThreadPoolExecutor(int corePoolSize,ThreadFactory threadFactory) {super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,new DelayedWorkQueue(), threadFactory);}由于ThreadPoolExecutor中的最大线程数是Integer.MAX_VALUE,所以容易造成OOM这里的super对应的就是ThreadPoolExecutor,用法跟其他三个区别
