這或許是最詳細的JUC多線程併發總結

多線程進階---JUC併發編程

完整代碼傳送門,見文章末尾html

1.Lock鎖(重點)

傳統 Synchronizdjava

package com.godfrey.demo01;

/**
 * description : 模擬賣票
 *
 * @author godfrey
 * @since 2020-05-14
 */
public class SaleTicketDemo01 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                ticket.sale();
            }
        }, "C").start();
    }
}

//資源類OOP
class Ticket {
    private int number = 50;

    public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "賣出了第" + (50 - (number--)) + "票,剩餘:" + number);
        }
    }
}

Synchronized(本質:隊列+鎖)和Lock區別git

  1. Synchronized 是內置關鍵字,Lock 是一個Java類程序員

  2. Synchronized 沒法判斷鎖的狀態,Lock 能夠判斷是否獲取到了鎖github

  3. Synchronized 會自動釋放鎖,Lock 必須手動釋放!若是不釋放鎖,死鎖ajax

  4. Synchronized 線程1(得到鎖,阻塞)、線程2(等待,傻傻的等);Lock 鎖就不必定會等待下去(tryLock)編程

  5. Synchronized 可重入鎖,不可中斷,非公平;Lock 可重入鎖 ,能夠判斷鎖,非公平(能夠本身設置);緩存

  6. Synchronized 適合鎖少許的代碼同步問題,Lock 適合鎖大量的同步代碼!安全

鎖是什麼,如何判斷鎖的是誰多線程

2.線程之間通訊問題:生成者消費者問題

Synchronized版生產者消費者問題

package proc;

/**
 * description : 生產者消費者問題
 *
 * @author godfrey
 * @since 2020-05-14
 */
public class A {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

// 判斷等待,業務,通知
class Data {
    private int number = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        if (number != 0) {
            //等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        //通知其餘線程,我+1完畢了
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        if (number == 0) {
            //等待
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        //通知其餘線程,我-1完畢了
        this.notifyAll();
    }
}

Lock接口

公平鎖:十分公平:能夠先來後到
非公平鎖:十分不公平:能夠插隊 (默認)

package com.godfrey.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * description : 模擬賣票
 *
 * @author godfrey
 * @since 2020-05-14
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale(); }, "A").start();
        new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale(); }, "B").start();
        new Thread(() -> { for (int i = 0; i < 40; i++) ticket.sale(); }, "C").start();
    }
}

//Lock
class Ticket2 {
    private int number = 30;

    Lock lock = new ReentrantLock();

    public synchronized void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "賣出了第" + (50 - (number--)) + "票,剩餘:" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

問題存在,ABCD四個線程!怎麼解決?

if ==>while

package com.godfrey.proc;

/**
 * description : Synchronized版生成者消費者問題
 *
 * @author godfrey
 * @since 2020-05-14
 */
public class A {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

// 判斷等待,業務,通知
class Data {
    private int number = 0;

    //+1
    public synchronized void increment() throws InterruptedException {
        while (number != 0) {
            //等待
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        //通知其餘線程,我+1完畢了
        this.notifyAll();
    }

    //-1
    public synchronized void decrement() throws InterruptedException {
        while (number == 0) {
            //等待
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "==>" + number);
        //通知其餘線程,我-1完畢了
        this.notifyAll();
    }
}

JUC版的生產者和消費者問題

經過Lock

package com.godfrey.proc;

/**
 * description : Lock版生產者消費者問題
 *
 * @author godfrey
 * @since 2020-05-14
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {
    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

// 判斷等待,業務,通知
class Data2 {
    private int number = 0;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    //+1
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) {
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "==>" + number);
            //通知其餘線程,我+1完畢了
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    //-1
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number == 0) {
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "==>" + number);
            //通知其餘線程,我-1完畢了
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

Condition的優點:精準通知和喚醒線程

.

package com.godfrey.proc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * description : 按順序執行 A->B->C
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class C {
    public static void main(String[] args) {
        Data3 data = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printA();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printB();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data.printC();
            }
        }, "C").start();
    }
}

//資源類
class Data3 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    private int number = 1; //1A 2B 3C

    public void printA() {
        lock.lock();
        try {
            //業務,判斷->執行->通知
            while (number != 1) {
                //等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>AAAAA");
            //通知指定的人,B
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            //業務,判斷->執行->通知
            while (number != 2) {
                //等待
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>BBBBB");
            //通知指定的人,C
            number = 3;
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            //業務,判斷->執行->通知
            while (number != 3) {
                //等待
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName() + "=>CCCCC");
            //通知指定的人,C
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

3.八鎖現象

package com.godfrey.lock8;

import java.util.concurrent.TimeUnit;

/**
 * description : 8鎖:關於鎖的8個問題
 * 1.標準狀況下 ,兩個線程先打印發短信仍是打電話? 1/發短信 2/打電話
 * 2.sendSms延時4秒 ,兩個線程先打印發短信仍是打電話? 1/發短信 2/打電話
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class Test1 {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(() -> {
            phone.sendSms();
        }, "A").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            phone.call();
        }, "B").start();
    }
}

class Phone {
    //synchronized 鎖的對象是方法的調用者!
    public synchronized void sendSms() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("發短信");
    }

    public synchronized void call() {
        System.out.println("打電話");
    }
}
package com.godfrey.lock8;

import java.util.concurrent.TimeUnit;

/**
 * description : 8鎖:關於鎖的8個問題
 * 3.增長了一個普通方法後!先執行發短信仍是Hello? 普通方法
 * 4.建立兩個對象,!先執行發短信仍是打電話? 打電話
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class Test2 {
    public static void main(String[] args) {
        //兩個對象,兩個調用者,兩把鎖
        Phone2 phone1 = new Phone2();
        Phone2 phone2 = new Phone2();

        new Thread(() -> {
            phone1.sendSms();
        }, "A").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            //phone1.hello();
            phone2.call();
        }, "B").start();
    }
}

class Phone2 {
    //synchronized 鎖的對象是方法的調用者!
    public synchronized void sendSms() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("發短信");
    }

    public synchronized void call() {
        System.out.println("打電話");
    }

    //這裏沒有鎖!不是同步方法,不受鎖的影響
    public void hello() {
        System.out.println("Hello");
    }
}
package com.godfrey.lock8;

import java.util.concurrent.TimeUnit;

/**
 * description : 8鎖:關於鎖的8個問題
 * 5.增長兩個靜態的同步方法,只要一個對象,先打樣發短信仍是打電話? 發短信
 * 6.兩個對象,增長兩個靜態的同步方法,只要一個對象,先打樣發短信仍是打電話? 發短信
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class Test3 {
    public static void main(String[] args) {
        //兩個對象,兩個調用者,兩把鎖
        //static 靜態方法
        //類一加載就有了!鎖的是class
        //Phone3 phone = new Phone3();
        Phone3 phone1 = new Phone3();
        Phone3 phone2 = new Phone3();

        new Thread(() -> {
            //phone.sendSms();
            phone1.sendSms();
        }, "A").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            phone2.call();
        }, "B").start();
    }
}

class Phone3 {
    //synchronized 鎖的對象是方法的調用者!
    public static synchronized void sendSms() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("發短信");
    }

    public static synchronized void call() {
        System.out.println("打電話");
    }
}
package com.godfrey.lock8;

import java.util.concurrent.TimeUnit;

/**
 * description : 8鎖:關於鎖的8個問題
 * 7.一個靜態同步方法一個普通方法,先打樣發短信仍是打電話? 打電話
 * 8.一個靜態同步方法一個普通方法,兩個對象,先打樣發短信仍是打電話? 打電話
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class Test4 {
    public static void main(String[] args) {
        //Phone4 phone = new Phone4();
        Phone4 phone1 = new Phone4();
        Phone4 phone2 = new Phone4();

        new Thread(() -> {
            //phone.sendSms();
            phone1.sendSms();
        }, "A").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            phone2.call();
        }, "B").start();
    }
}

class Phone4 {
    //靜態同步方法,鎖的對象是Class模板!
    public static synchronized void sendSms() {
        try {
            TimeUnit.SECONDS.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("發短信");
    }

    //普通同步方法,鎖的是調用者
    public synchronized void call() {
        System.out.println("打電話");
    }
}

小結:看鎖的是Class仍是對象,看是否同一個調用者

4.集合類不安全

List不安全

package com.godfrey.unsafe;

import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * description : java.util.ConcurrentModificationException 併發修改異常
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class ListTest {
    public static void main(String[] args) {
        //併發下 ArrayList不安全的
        /**
         * 解決方案:
         * 1.List<String> list = new Vector<>();
         * 2.List<String> list = Collections.synchronizedList(new ArrayList<>());
         * 3.List<String> list = new CopyOnWriteArrayList<>();
         */

        //CopyOnWrite 寫入時複製COW 計算機程序設計 領域的一種優化策略
        //多個線程調用的時候,list, 讀取的時候,固定的,寫入(覆蓋)
        //在寫入的時候避免覆蓋,形成數據問題!
        //讀寫分離
        //CopyOnWriteArrayList 比 Vector 牛逼在哪裏?CopyOnWriteArrayList用Lock,Vector用Synchronized

        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(list);
            }, String.valueOf(i)).start();
        }
    }
}

Set不安全

package com.godfrey.unsafe;

import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * description : java.util.ConcurrentModificationException 併發修改異常
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class SetTest {
    public static void main(String[] args) {
        //HashSet<String> set = new HashSet<>();
        //併發下 HashSet不安全的
        /**
         * 解決方案:
         * 1. Set<String> set = Collections.synchronizedSet(new HashSet<>());
         * 2. Set<String> set = new CopyOnWriteArraySet<>();
         */

        Set<String> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0, 5));
                System.out.println(set);
            }, String.valueOf(i)).start();
        }
    }
}

問:HashSet的底層是什麼?

答:HashMap

public HashSet() {
    map = new HashMap<>();
}

//add set的本質是map key
public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

private static final Object PRESENT = new Object();

Map不安全

package com.godfrey.unsafe;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description : java.util.ConcurrentModificationException 併發修改異常
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class MapTest {
    public static void main(String[] args) {
        // Map<String, String> map= new HashMap<>();
        // 等價於 Map<String, String> map = new HashMap<>(16,0.75f);//加載因子,初始化容量


        //併發下 HashMap不安全的
        /**
         * 解決方案:
         * 1.Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
         * 2.Map<String, String> map = new ConcurrentHashMap<>();
         */
        Map<String, String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 5));
                System.out.println(map);
            }, String.valueOf(i)).start();
        }
    }
}

5.Callable

  1. 有返回值
  2. 能夠拋出異常
  3. 方法不一樣,run()/call()

代碼測試

.

package com.godfrey.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * description : Callable測試
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //new Thread(new Runnable).start();
        //new Thread(new FutureTask<V>()).start();
        //new Thread(new FutureTask<V>(Callable)).start();

        MyThread thread = new MyThread();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(thread);//適配類

        new Thread(futureTask, "A").start();
        new Thread(futureTask, "B").start();//結果會被緩存,提升效率,最後打印只有一份
        
        Integer integer = futureTask.get();//獲取Callable的返回結果(get方法可能會產生阻塞【大數據等待返回結果慢】!把它放到最會,或者用異步通訊)
        System.out.println(integer);
    }
}

class MyThread implements Callable<Integer> {
    @Override
    public Integer call() {
        System.out.println("call()");
        return 1024;
    }
}

細節:

  1. 有緩存
  2. get(),結果可能會等待,會阻塞

6.經常使用輔助類(必會)

6.1 CountDownLatch

package com.godfrey.add;

import java.util.concurrent.CountDownLatch;

/**
 * description : 減法計數器
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        //總數是6
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "\tGo Out");
                countDownLatch.countDown();//-1
            }, String.valueOf(i)).start();
        }

        countDownLatch.await();//等待計數器歸零,而後再向下執行
        System.out.println("Close Door");
    }
}

原理:

countDownLatch.countDown() //數量-1

countDownLatch.await() //等待計數器歸零,而後再向下執行

每次有線程調用countDown()數量-1 , 假設計數器變爲0 , countDownLatch.await()就會被喚醒,繼續執行!

6.2 CyclicBarrier

加法計數器

package com.godfrey.add;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * description : 加法計數器
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /**
         * 集齊七顆龍珠召喚神龍
         * 集齊龍珠的線程
         */
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println("召喚神龍成功");
        });

        for (int i = 0; i < 7; i++) {
            final int temp = i;//lambda操做不到i
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "收集" + temp + "個龍珠");

                try {
                    cyclicBarrier.await();//等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }
}

6.3 Semaphore

Semaphore:信號量

搶車位!

package com.godfrey.add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * description : 信號量
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        //線程數量:停車位! 限流!
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(() -> {
                //acquire() 獲得
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "搶到車位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "離開車位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //release() 釋放
                    semaphore.release();
                }

            }).start();
        }
    }
}

原理:

semaphore.acquire() 得到,假設若是已經滿了, 等待,等待被釋放爲止!

semaphore.release() 釋放,會將當前的信號量釋放+ 1 ,而後喚醒等待的線程!

做用:

  1. 多個共享資源互斥的使用!
  2. 併發限流,控制最大的線程數!

7.讀寫鎖

ReadWriteLock

package com.godfrey.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * description : 讀寫鎖
 * 獨佔鎖(寫鎖) 一次只能被一個線程佔有
 * 共享鎖(讀鎖) 多個線程能夠同時佔有
 * ReadWriteLock
 * 讀-讀 能夠共存!
 * 讀-寫 不能共存!
 * 寫-寫 不能共存!
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCacheLock myCache = new MyCacheLock();

        //寫入
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }

        //讀取
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get(temp + "");
            }, String.valueOf(i)).start();
        }
    }
}

//加鎖的
class MyCacheLock {
    private volatile Map<String, Object> map = new HashMap<>();
    //讀寫鎖,更加細粒度的控制
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 存,寫入的時候,只但願同時只有一個線程寫
    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "寫入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "寫入OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }

    }

    // 取,讀,全部人均可以
    public void get(String key) {
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "讀入" + key);
            Object o = map.get(key);
            System.out.println(Thread.currentThread().getName() + "讀入OK");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
}

/**
 * 自定義緩存
 */
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    //存,寫
    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "寫入" + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "寫入OK");
    }

    //取,讀
    public void get(String key) {
        System.out.println(Thread.currentThread().getName() + "讀入" + key);
        Object o = map.get(key);
        System.out.println(Thread.currentThread().getName() + "讀入OK");
    }
}

8.阻塞隊列

阻塞隊列:

什麼狀況下咱們會使用 阻塞隊列:多線程併發處理,線程池!
學會使用隊列
添加、移除
四組API

方式 拋出異常 有返回值,不拋出異常 阻塞 等待 超時
添加 add offer put offer
移除 remove poll take poll
判斷隊列的首部 element peek - -
/**
 * 拋出異常
 */
public static void test1() {
    ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
    System.out.println(blockingQueue.add("a"));
    System.out.println(blockingQueue.add("b"));
    System.out.println(blockingQueue.add("c"));

    //ava.lang.IllegalStateException: Queue full  拋出異常!隊列已滿
    //System.out.println(blockingQueue.add("d"));

    System.out.println(blockingQueue.element());//查看隊首元素是誰
    System.out.println("===================");

    System.out.println(blockingQueue.remove());
    System.out.println(blockingQueue.remove());
    System.out.println(blockingQueue.remove());
    //java.lang.IllegalStateException: Queue full 拋出異常!隊列爲空
    //System.out.println(blockingQueue.remove());
}
/**
 * 有返回值,沒有異常
 */
public static void test2() {
    ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
    System.out.println(blockingQueue.offer("a"));
    System.out.println(blockingQueue.offer("b"));
    System.out.println(blockingQueue.offer("c"));

    //System.out.println(blockingQueue.offer("d"));// false 不拋出異常!

    System.out.println(blockingQueue.peek());//查看隊首元素是誰
    System.out.println("===================");

    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
    //System.out.println(blockingQueue.remove());// null 不拋出異常!
}
/**
 * 等待,阻塞(一直阻塞)
 */
public static void test3() throws InterruptedException {
    // 隊列的大小
    ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

    // 一直阻塞
    blockingQueue.put("a");
    blockingQueue.put("b");
    blockingQueue.put("c");
    // blockingQueue.put("d"); // 隊列沒有位置了,一直阻塞
    System.out.println(blockingQueue.take());
    System.out.println(blockingQueue.take());
    System.out.println(blockingQueue.take());
    System.out.println(blockingQueue.take()); // 沒有這個元素,一直阻塞
}
/**
 * 等待,阻塞(等待超市)
 */
public static void test4() throws InterruptedException {
    ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);
    blockingQueue.offer("a");
    blockingQueue.offer("b");
    blockingQueue.offer("c");

    // blockingQueue.offer("d",2,TimeUnit.SECONDS); // 等待超過2秒就退出
    System.out.println("===============");
    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
    System.out.println(blockingQueue.poll());
    blockingQueue.poll(2, TimeUnit.SECONDS); // 等待超過2秒就退出
}

SynchronousQueue 同步隊列

沒有容量,
進去一個元素,必須等待取出來以後,才能再往裏面放一個元素!
put、take

package com.godfrey.bq;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;
/**
 * description :
 *
 * @author godfrey
 * @since 2020-05-15
 */

/**
 * 同步隊列
 * 和其餘的BlockingQueue 不同, SynchronousQueue 不存儲元素
 * put了一個元素,必須從裏面先take取出來,不然不能在put進去值!
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        BlockingQueue<String> blockingQueue = new SynchronousQueue<>(); // 同步隊列

        new Thread(() -> {
            try {
                blockingQueue.put("1");
                System.out.println(Thread.currentThread().getName() + " put 1");
                blockingQueue.put("2");
                System.out.println(Thread.currentThread().getName() + " put 2");
                blockingQueue.put("3");
                System.out.println(Thread.currentThread().getName() + " put 3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1").start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "=>" + blockingQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();
    }
}

9.線程池(重點)

線程池:三大方法、7大參數、4種拒絕策略

池話技術

程序的運行,本質:佔用系統的資源! 優化資源的使用!=>池化技術
線程池、鏈接池、內存池、對象池///..... 建立、銷燬。十分浪費資源
池化技術:事先準備好一些資源,有人要用,就來我這裏拿,用完以後還給我

線程池的好處:

  1. 下降資源的消耗
  2. 提升響應的速度
  3. 方便管理

線程複用、能夠控制最大併發數、管理線程

三大方法

package com.godfrey.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * description : Executors 工具類、3大方法
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class Demo01 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newSingleThreadExecutor();// 單個線程
        //ExecutorService threadPool = Executors.newFixedThreadPool(5);// 建立一個固定的線程池的大小
        //ExecutorService threadPool = Executors.newCachedThreadPool();// 可伸縮的,遇強則強,遇弱則弱

        try {
            for (int i = 0; i < 100; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\tOK");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 線程池用完,程序結束,關閉線程池
            threadPool.shutdown();
        }
    }
}

七大參數

源碼分析:

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}



//本質ThreadPoolExecutor()

public ThreadPoolExecutor(int corePoolSize, // 核心線程池大小
                          int maximumPoolSize, // 最大核心線程池大小
                          long keepAliveTime, // 超時了沒有人調用就會釋放
                          TimeUnit unit, // 超時單位
                          BlockingQueue<Runnable> workQueue, // 阻塞隊列
                          ThreadFactory threadFactory, // 線程工廠:建立線程的,通常不用動
                          RejectedExecutionHandler handler // 拒絕策略) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

手寫一個線程池

package com.godfrey.pool;

import java.util.concurrent.*;

/**
 * description : 七大參數與四種拒絕策略
 * 四種拒絕策略:
 * AbortPolicy(默認):隊列滿了,還有任務進來,不處理這個任務的,直接拋出 RejectedExecution異常!
 * CallerRunsPolicy:哪來的回哪裏!
 * DiscardOldestPolicy:隊列滿了,拋棄隊列中等待最久的任務,而後把當前任務加入隊列中嘗試再次提交
 * DiscardPolicy():隊列滿了,直接丟棄任務,不予任何處理也不拋出異常.若是容許任務丟失,這是最好的拒絕策略!
 *
 * @author godfrey
 * @since 2020-05-15
 */
public class Demo02 {
    public static void main(String[] args) {
        ExecutorService threadPool = new ThreadPoolExecutor(
                //模擬銀行業務辦理
                2,   //常駐核心線程數     辦理業務窗口初始數量
                5, //線程池可以容納同時執行的最大線程數,此值大於等於1,  辦理業務窗口最大數量
                3, //多餘的空閒線程存活時間,當空間時間達到keepAliveTime值時,多餘的線程會被銷燬直到只剩下corePoolSize個線程爲止    釋放後窗口數量會變爲常駐核心數
                TimeUnit.SECONDS, //超時單位
                new LinkedBlockingDeque<>(3), //任務隊列,被提交但還沒有被執行的任務.  候客區座位數量
                Executors.defaultThreadFactory(), //線程工廠:建立線程的,通常不用動
                new ThreadPoolExecutor.DiscardOldestPolicy()); //拒絕策略,表示當線程隊列滿了而且工做線程大於等於線程池的最大顯示 數(maxnumPoolSize)時如何來拒絕

        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\tOK");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 線程池用完,程序結束,關閉線程池
            threadPool.shutdown();
        }
    }
}

四種拒絕策略

  1. AbortPolicy(默認):隊列滿了,還有任務進來,不處理這個任務的,直接拋出 RejectedExecution異常
  2. CallerRunsPolicy:哪來的回哪裏!
  3. DiscardOldestPolicy:隊列滿了,拋棄隊列中等待最久的任務,而後把當前任務加入隊列中嘗試再次提交
  4. DiscardPolicy():隊列滿了,直接丟棄任務,不予任何處理也不拋出異常.若是容許任務丟失,這是最好的拒絕策略!

小結和拓展

池的最大的大小如何去設置!

獲取CPU核數System.out.println(Runtime.getRuntime().availableProcessors())

瞭解:用來(調優)

  • CPU密集型:CPU核數+1
  • IO密集型:
    • CPU核數*2
    • CPU核數/1.0-阻塞係數 阻塞係數在0.8~0.9之間

10.四大函數式接口(必需掌握)

新時代的程序員:lambda表達式、鏈式編程、函數式接口、Stream流式計算

函數式接口:只有一個方法的接口

@FunctionalInterface
public interface Runnable {
    public abstract void run();
}

.

代碼測試

函數式接口

package com.godfrey.function;

import java.util.function.Function;

/**
 * description : Function 函數式接口,有一個輸入參數,有一個輸出
 * 只要是 函數型接口 能夠 用 lambda表達式簡化
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo01 {
    public static void main(String[] args) {
        //Function function = new Function<String, String>(){
        //    @Override
        //    public String apply(String o) {
        //        return o;
        //    }
        //};
        
        Function function = str->{return str;};

        System.out.println(function.apply("123"));
    }
}

判定型接口:有一個輸入參數,返回值只能是 布爾值!

.

package com.godfrey.function;

import java.util.function.Predicate;

/**
 * description : 判定型接口,有一個輸入參數,返回值只能是布爾值!
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo02 {
    public static void main(String[] args) {
        //判斷字符串是否爲空
        //Predicate<String> predicate = new Predicate<String>() {
        //    @Override
        //    public boolean test(String str) {
        //        return str.isEmpty();
        //    }
        //};

        Predicate<String> predicate = str -> { return str.isEmpty(); };
        System.out.println(predicate.test(""));
    }
}

Consumer 消費型接口

.

package com.godfrey.function;

import java.util.function.Consumer;

/**
 * description : Consumer 消費型接口,只有輸入,沒有返回值
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo03 {
    public static void main(String[] args) {
        //Consumer<String> consumer = new Consumer<String>() {
        //    @Override
        //    public void accept(String str) {
        //        System.out.println(str);
        //    }
        //};
        Consumer<String> consumer = str -> System.out.println(str);
        consumer.accept("godfrey");
    }
}

Supplier 供給型接口

.

package com.godfrey.function;

import java.util.function.Supplier;

/**
 * description : Supplier 供給型接口,沒有參數,只有返回值
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo04 {
    public static void main(String[] args) {
        //Supplier supplier = new Supplier<Integer>() {
        //    @Override
        //    public Integer get() {
        //        System.out.println("get()");
        //        return 1024;
        //    }
        //};
        Supplier supplier = () -> { return 1024;};
        System.out.println(supplier.get());
    }
}

11.Stream流式計算

什麼是Stream流式計算

大數據:存儲 + 計算
集合、MySQL 本質就是存儲東西的;
計算都應該交給流來操做!

.

package com.godfrey.stream;

import java.util.Arrays;
import java.util.List;

/**
 * description :一分鐘內完成此題,只能用一行代碼實現!
 * 如今有5個用戶!篩選:
 * 一、ID 必須是偶數
 * 二、年齡必須大於23歲
 * 三、用戶名轉爲大寫字母
 * 四、用戶名字母倒着排序
 * 五、只輸出一個用戶!
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Test {
    public static void main(String[] args) {
        User u1 = new User(1, "a", 21);
        User u2 = new User(2, "b", 22);
        User u3 = new User(3, "c", 23);
        User u4 = new User(4, "d", 24);
        User u5 = new User(6, "e", 25);

        //集合就算存儲
        List<User> list = Arrays.asList(u1, u2, u3, u4, u5);

        //計算交給Stream流
        list.stream()
                .filter(u -> { return u.getId() % 2 == 0; })
                .filter(u->{return u.getAge()>23;})
                .map(u->{return u.getName().toUpperCase();})
                .sorted((uu1,uu2)->{return uu2.compareTo(uu1);})
                .limit(1)
                .forEach(System.out::println);
    }
}

12.ForkJoin

什麼是 ForkJoin

ForkJoin 在 JDK 1.7 , 並行執行任務!提升效率。大數據量!
大數據:Map Reduce (把大任務拆分爲小任務)

ForkJoin 特色:工做竊取

這個裏面維護的都是雙端隊列

.

Forkjoin

.

package com.godfrey.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * 求和計算的任務!
 * 如何使用 forkjoin
 * 一、forkjoinPool 經過它來執行
 * 二、計算任務 forkjoinPool.execute(ForkJoinTask task)
 * 三、 計算類要繼承 ForkJoinTask
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class ForkJoinDemo extends RecursiveTask<Long> {
    private Long start;
    private Long end;

    //臨界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }


    //計算方法
    @Override
    protected Long compute() {
        if ((end - start) > temp) {
            Long sum = 0L;
            for (Long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else { // forkjoin 遞歸
            Long middle = (start + end) / 2;//中間值
            ForkJoinDemo task1 = new ForkJoinDemo(start, middle);
            task1.fork(); // 拆分任務,把任務壓入線程隊列
            ForkJoinDemo task2 = new ForkJoinDemo(middle + 1, end);
            task2.fork(); // 拆分任務,把任務壓入線程隊列
            return task1.join() + task2.join();
        }
    }
}

測試:

package com.godfrey.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * description : 效率測試
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1();  //sum=499999999500000000 時間:7192
        //test2();  //sum=499999999500000000 時間:6949
        test3();    //sum=500000000500000000 時間:526
    }

    // 普通程序員
    public static void test1() {
        Long sum = 0L;
        Long start = System.currentTimeMillis();
        for (Long i = 0L; i < 10_0000_0000L; i++) {
            sum += i;
        }
        Long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 時間:" + (end - start));
    }

    //ForkJoin
    public static void test2() throws ExecutionException, InterruptedException {
        Long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        Long sum = submit.get();

        Long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 時間:" + (end - start));
    }

    //Stream並行流
    public static void test3() {
        Long start = System.currentTimeMillis();

        Long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum);
        Long end = System.currentTimeMillis();
        System.out.println("sum=" + sum + " 時間:" + (end - start));
    }
}

13.異步回調

Future 設計的初衷: 對未來的某個事件的結果進行建模

package com.godfrey.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * description : 異步回調
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo01 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1();
        test02();
    }

    // 沒有返回值的 runAsync 異步回調
    public static void test1() throws InterruptedException, ExecutionException {

        CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "runAsync=>Void");
        });
        System.out.println("1111");
        completableFuture.get(); // 獲取阻塞執行結果
    }

    // 有返回值的 supplyAsync 異步回調
    // ajax,成功和失敗的回調
    // 返回的是錯誤信息;
    public static void test02() throws InterruptedException, ExecutionException {

        CompletableFuture<Integer> completableFuture =
                CompletableFuture.supplyAsync(() -> {
                    System.out.println(Thread.currentThread().getName() + "supplyAsync=>Integer");
                    int i = 10 / 0;
                    return 1024;
                });
        System.out.println(completableFuture.whenComplete((t, u) -> {
            System.out.println("t=>" + t); // 正常的返回結果
            System.out.println("u=>" + u); // 錯誤信息:java.util.concurrent.CompletionException:java.lang.ArithmeticException: / by zero

        }).exceptionally((e) -> {
            System.out.println(e.getMessage());
            return 233; // 能夠獲取到錯誤的返回結果
        }).get());
        /**
         * succee Code 200
         * error Code 404 500
         */}
}

14.JMM

請你談談你對 Volatile 的理解

Volatile 是 Java 虛擬機提供輕量級的同步機制

  1. 保證可見性
  2. 不保證原子性
  3. 禁止指令重排

什麼是JMM

JMM : Java內存模型,不存在的東西,概念!約定!

關於JMM的一些同步的約定:

  1. 線程解鎖前,必須把共享變量馬上刷回主存
  2. 線程加鎖前,必須讀取主存中的最新值到工做內存中!
  3. 加鎖和解鎖是同一把鎖

線程 工做內存 、主內存

8種操做:

內存交互操做有8種,虛擬機實現必須保證每個操做都是原子的,不可再分的(對於double和long類
型的變量來講,load、store、read和write操做在某些平臺上容許例外)

  • lock (鎖定):做用於主內存的變量,把一個變量標識爲線程獨佔狀態
  • unlock (解鎖):做用於主內存的變量,它把一個處於鎖定狀態的變量釋放出來,釋放後的變量才能夠被其餘線程鎖定
  • read (讀取):做用於主內存變量,它把一個變量的值從主內存傳輸到線程的工做內存中,以便隨後的load動做使用
  • load (載入):做用於工做內存的變量,它把read操做從主存中變量放入工做內存中
  • use (使用):做用於工做內存中的變量,它把工做內存中的變量傳輸給執行引擎,每當虛擬機遇到一個須要使用到變量的值,就會使用到這個指令
  • assign (賦值):做用於工做內存中的變量,它把一個從執行引擎中接受到的值放入工做內存的變量副本中
  • store (存儲):做用於主內存中的變量,它把一個從工做內存中一個變量的值傳送到主內存中,以便後續的write使用
  • write (寫入):做用於主內存中的變量,它把store操做從工做內存中獲得的變量的值放入主內存的變量中

JMM對這八種指令的使用,制定了以下規則:

  • 不容許read和load、store和write操做之一單獨出現。即便用了read必須load,使用了store必須write
  • 不容許線程丟棄他最近的assign操做,即工做變量的數據改變了以後,必須告知主存
  • 不容許一個線程將沒有assign的數據從工做內存同步回主內存
  • 一個新的變量必須在主內存中誕生,不容許工做內存直接使用一個未被初始化的變量。就是懟變量
    實施use、store操做以前,必須通過assign和load操做
  • 一個變量同一時間只有一個線程能對其進行lock。屢次lock後,必須執行相同次數的unlock才能解鎖
  • 若是對一個變量進行lock操做,會清空全部工做內存中此變量的值,在執行引擎使用這個變量前,必須從新load或assign操做初始化變量的值
  • 若是一個變量沒有被lock,就不能對其進行unlock操做。也不能unlock一個被其餘線程鎖住的變量
  • 對一個變量進行unlock操做以前,必須把此變量同步回主內存

15.Volatile

1.保證可見性

package com.godfrey.tvolatile;

import java.util.concurrent.TimeUnit;

/**
 * description : volatile 保證可見性
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class JMMDemo {
    // 不加 volatile 程序就會死循環!
    // 加 volatile 能夠保證可見性
    private volatile static int num = 0;

    public static void main(String[] args) { // main
        new Thread(() -> { // 線程 1 對主內存的變化不知道的
            while (num == 0) {
            }
        }).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        num = 1;
        System.out.println(num);
    }
}

2.不保證原子性

原子性 : 不可分割
線程A在執行任務的時候,不能被打擾的,也不能被分割。要麼同時成功,要麼同時失敗

package com.godfrey.tvolatile;

/**
 * description : volatile 不保證原子性
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class JMMDemo {
    private volatile static int num = 0;

    public static void add() {
        num++;
    }

    public static void main(String[] args) {
        //理論上num結果應該爲 2 萬
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount() > 2) { // main gc
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + " " + num);
    }
}

若是不加 lock 和 synchronized ,怎麼樣保證原子性

使用原子類,解決原子性問題

.

package com.godfrey.tvolatile;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * description : volatile 不保證原子性
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class VDemo02 {
    // volatile 不保證原子性
    // 原子類的 Integer
    private volatile static AtomicInteger num = new AtomicInteger();

    public static void add() {
        // num++; // 不是一個原子性操做
        num.getAndIncrement(); // AtomicInteger + 1 方法, CAS
    }

    public static void main(String[] args) {
        //理論上num結果應該爲 2 萬
        for (int i = 0; i < 20; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    add();
                }
            }).start();
        }
        while (Thread.activeCount() > 2) { // main gc
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + " " + num);
    }
}

這些類的底層都直接和操做系統掛鉤!在內存中修改值!Unsafe類是一個很特殊的存在!

指令重排

什麼是 指令重排:你寫的程序,計算機並非按照你寫的那樣去執行的
源代碼-->編譯器優化的重排--> 指令並行也可能會重排--> 內存系統也會重排---> 執行

處理器在進行指令重排的時候,考慮:數據之間的依賴性!

int x = 1; // 1
int y = 2; // 2
x = x + 5; // 3
y = x * x; // 4
咱們所指望的:1234 可是可能執行的時候回變成 2134 1324
可不多是 4123!

可能形成影響的結果: a b x y 這四個值默認都是 0;

線程A 線程B
x=a y=b
b=1 a=2

正常的結果: x = 0;y = 0;可是可能因爲指令重排

線程A 線程B
b=1 a=2
x=a y=b

指令重排致使的詭異結果: x = 2;y = 1;

禁止指令重排

volatile能夠禁止指令重排:

內存屏障。CPU指令。做用:

  1. 保證特定的操做的執行順序!
  2. 能夠保證某些變量的內存可見性 (利用這些特性volatile實現了可見性)

.

Volatile 是能夠保持 可見性。不能保證原子性,因爲內存屏障,能夠保證避免指令重排的現象產生!

16.完全玩轉單例模式

餓漢式 DCL懶漢式,深究!

餓漢式

package com.godfrey.single;

/**
 * description : 餓漢式單例
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Hungry {
    private Hungry() {
        
    }

    public final static Hungry HUNGRY = new Hungry();

    public static Hungry getInstance() {
        return HUNGRY;
    }
}

靜態內部類

package com.godfrey.single;

/**
 * description : 靜態內部類單例
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Holder {
    private Holder() {

    }

    private static class InnerClass {
        private final static Holder HOLDER = new Holder();
    }

    public static Holder getInstance() {
        return InnerClass.HOLDER;
    }
}

單例不安全,反射

枚舉

package com.godfrey.single;

/**
 * description : 枚舉單例
 *
 * @author godfrey
 * @since 2020-05-16
 */
public enum EnumSingle {
    INSTANCE;
}

經過class文件反編譯獲得Java文件:

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 
// Source File Name:   EnumSingle.java

package com.godfrey.single;

import java.io.PrintStream;

public final class EnumSingle extends Enum
{

    public static EnumSingle[] values()
    {
        return (EnumSingle[])$VALUES.clone();
    }

    public static EnumSingle valueOf(String name)
    {
        return (EnumSingle)Enum.valueOf(com/godfrey/single/EnumSingle, name);
    }

    private EnumSingle(String s, int i)
    {
        super(s, i);
    }

    public static void main(String args[])
    {
        System.out.println(INSTANCE);
    }

    public static final EnumSingle INSTANCE;
    private static final EnumSingle $VALUES[];

    static 
    {
        INSTANCE = new EnumSingle("INSTANCE", 0);
        $VALUES = (new EnumSingle[] {
            INSTANCE
        });
    }
}

能夠發現枚舉的單例構造器是有參

17.深刻理解CAS

什麼是 CAS

package com.godfrey.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * description : CAS compareAndSet : 比較並交換
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class CASDemo {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);

        // 指望、更新
        // public final boolean compareAndSet(int expectedValue, int newValue)
        // 若是我指望的值達到了,那麼就更新,不然,就不更新, CAS 是CPU的併發原語!

        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        atomicInteger.getAndIncrement();
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
    }
}

Unsafe 類

CAS : 比較當前工做內存中的值和主內存中的值,若是這個值是指望的,那麼則執行操做!若是不是就一直循環!
缺點:

  1. 循環會耗時
  2. 一次性只能保證一個共享變量的原子性
  3. ABA問題

CAS : ABA 問題(狸貓換太子)

package com.godfrey.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * description : CAS問題:ABA(狸貓換太子)
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class ABADemo {
    // CAS compareAndSet : 比較並交換!
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);

        // 指望、更新
        // public final boolean compareAndSet(int expect, int update)
        // 若是我指望的值達到了,那麼就更新,不然,就不更新, CAS 是CPU的併發原語!
        // ============== 搗亂的線程 ==================
        System.out.println(atomicInteger.compareAndSet(2020, 2021));
        System.out.println(atomicInteger.get());
        System.out.println(atomicInteger.compareAndSet(2021, 2020));
        System.out.println(atomicInteger.get());
        // ============== 指望的線程 ==================
        System.out.println(atomicInteger.compareAndSet(2020, 6666));
        System.out.println(atomicInteger.get());
    }
}

18.原子引用

解決ABA 問題,引入原子引用! 對應的思想:樂觀鎖

帶版本號 的原子操做!

package com.godfrey.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * description : 原子引用解決ABA問題
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class AtomicStampedReferenceDemo {
    //AtomicStampedReference 注意,若是泛型是一個包裝類,注意對象的引用問題
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(1, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp(); // 得到版本號
            System.out.println("a1=>" + stamp);

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            atomicStampedReference.compareAndSet(1, 2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
            System.out.println("a2=>" + atomicStampedReference.getStamp());

            System.out.println(atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1));
            System.out.println("a3=>" + atomicStampedReference.getStamp());
        }, "a").start();

        // 樂觀鎖的原理相同!
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp(); // 得到版本號
            System.out.println("b1=>" + stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicStampedReference.compareAndSet(1, 6, stamp, stamp + 1));
            System.out.println("b2=>" + atomicStampedReference.getStamp());
        }, "b").start();
    }
}

注意:
Integer 使用了對象緩存機制,默認範圍是 -128 ~ 127 ,推薦使用靜態工廠方法 valueOf 獲取對象實例,而不是 new,由於 valueOf 使用緩存,而 new 必定會建立新的對象分配新的內存空間;

19.各類鎖的理解

1.公平鎖、非公平鎖

公平鎖: 很是公平, 不可以插隊,必須先來後到!
非公平鎖:很是不公平,能夠插隊 (默認都是非公平)

public ReentrantLock() {
	sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
	sync = fair ? new FairSync() : new NonfairSync();
}

2.可重入鎖

可重入鎖(遞歸鎖)

Synchronized

package com.godfrey.lock;

/**
 * description : Synchronized
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo01 {
    public static void main(String[] args) {
        Phone phone = new Phone();

        new Thread(() -> {
            phone.sms();
        }, "A").start();

        new Thread(() -> {
            phone.sms();
        }, "B").start();
    }
}

class Phone {
    public synchronized void sms() {
        System.out.println(Thread.currentThread().getName() + "sms");
        call(); // 這裏也有鎖
    }

    public synchronized void call() {
        System.out.println(Thread.currentThread().getName() + "call");
    }
}

Lock 版

package com.godfrey.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * description :
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class Demo02 {
    public static void main(String[] args) {
        Phone2 phone = new Phone2();
        new Thread(() -> {
            phone.sms();
        }, "A").start();

        new Thread(() -> {
            phone.sms();
        }, "B").start();
    }
}

class Phone2 {
    Lock lock = new ReentrantLock();

    public void sms() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "sms");
            call(); // 這裏也有鎖
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void call() {
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

3.自旋鎖

spinlock

咱們來自定義一個鎖測試

package com.godfrey.lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * description : 自旋鎖
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class SpinlockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    // 加鎖
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> mylock");

        // 自旋鎖
        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    // 解鎖
    public void myUnLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "==> myUnlock");
        atomicReference.compareAndSet(thread, null);
    }
}

測試

package com.godfrey.lock;

import java.util.concurrent.TimeUnit;

/**
 * description : 測試自定義CAS實現的自旋鎖
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class TestSpinLock {
    public static void main(String[] args) throws InterruptedException {
        // 底層使用的自旋鎖CAS
        SpinlockDemo lock = new SpinlockDemo();

        new Thread(() -> {
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        }, "T1").start();

        TimeUnit.SECONDS.sleep(1);
        new Thread(() -> {
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnLock();
            }
        }, "T2").start();
    }
}

.

4.死鎖

死鎖是什麼

死鎖測試,怎麼排除死鎖:

package com.godfrey.lock;

import java.util.concurrent.TimeUnit;

/**
 * description : 死鎖Demo
 *
 * @author godfrey
 * @since 2020-05-16
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new MyThread(lockA, lockB), "T1").start();
        new Thread(new MyThread(lockB, lockA), "T2").start();
    }
}

class MyThread implements Runnable {
    private String lockA;
    private String lockB;

    public MyThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() +
                    "lock:" + lockA + "=>get" + lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() +
                        "lock:" + lockB + "=>get" + lockA);
            }
        }
    }
}

解決問題

  1. 使用 jps -l 定位進程號

  1. 使用jstack 進程號找到死鎖問題

代碼傳送門:

相關文章
相關標籤/搜索