1. 程式人生 > 實用技巧 >【MySQL Database】資料庫複製--Replication

【MySQL Database】資料庫複製--Replication

多執行緒

一、執行緒簡介

1. Process與Thread

  • 程式-----(執行)------>程序---------->執行緒

    • 一個程序中包含若干個執行緒,執行緒是CPU排程和執行的單位
    • mian即主執行緒
  • 執行緒是獨立的執行路徑

  • 程式執行時,即使自己沒有建立執行緒,後臺也會有多個執行緒---主執行緒,gc執行緒

  • 一個程序中,如果開闢多個執行緒,執行緒的排程由排程器安排排程,而排程去與系統相關,人為無法干預

  • 對同一份資源,操作時,會存在資源搶奪的問題,需要加入併發控制

  • 執行緒會帶來額外開銷,如CPU排程時間,併發控制開銷

  • 每個執行緒只在自己的工作記憶體互動,互不干預

二、執行緒的實現(重點)

1. 執行緒的建立(三種方式)

① Thread類

  • 自定義執行緒類繼承Tread類

  • 重寫run()方法,編寫執行緒執行體

  • 建立執行緒物件,呼叫start()方法其拆散多執行緒

    //繼承Thread類
    public class TestThread1 extends Thread {
        //run方法——TestTread1執行緒
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                System.out.println("這是Testread1執行緒"+i);
            }
        }
    
        //main方法——主執行緒
        public static void main(String[] args) {
            TestThread1 testThread1 = new TestThread1();//建立執行緒
            testThread1.start();//開啟多執行緒
    
            for (int i = 0; i < 1000; i++) {
                System.out.println("這是主執行緒"+i);
            }
        }
    }
    

    執行緒開啟不一定立即執行,由CPU排程執行,人為無法干預

    testThread1.start()開啟多執行緒後,執行緒時交替執行的

    而testThread1.run()是呼叫TestThread1類中的run()方法,順序執行,因此run執行完後才執行main

    public class TestThread1 extends Thread {
        //run方法——TestTread1執行緒
        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                System.out.println("這是Testread1執行緒"+i);
            }
        }
    
        //main方法——主執行緒
        public static void main(String[] args) {
            TestThread1 testThread1 = new TestThread1();
            testThread1.run();//呼叫run方法
    
            for (int i = 0; i < 1000; i++) {
                System.out.println("這是主執行緒"+i);
            }
        }
    }
    
下載圖片

用多執行緒下載架包

  • 將commons-io 2.6拷僅idea的lib目錄

  • 右鍵add as library

    //練習Thread,實現多執行緒同步下載圖片
    public class TestThread2 extends Thread{
    
        private String url;//網路圖片地址
        private String name;//儲存的檔名
    
        public TestThread2(String url, String name) {
            this.url = url;
            this.name = name;
        }
    
        @Override
        public void run() {
            WebDownloader webDownloader = new WebDownloader();
            webDownloader.downloader(url,name);
            System.out.println("下載檔名為:"+name);
        }
    
        public static void main(String[] args) {
            TestThread2 t1 = new TestThread2("https://04imgmini.eastday.com/mobile/20201124/20201124125422_b97573c574f48a6af5f5c5c9a9beea1b_1.jpeg","aaa1.jpg");
            TestThread2 t2 = new TestThread2("https://04imgmini.eastday.com/mobile/20201124/20201124125422_b97573c574f48a6af5f5c5c9a9beea1b_2.jpeg","aaa2.jpg");
            TestThread2 t3 = new TestThread2("https://04imgmini.eastday.com/mobile/20201124/20201124125422_b97573c574f48a6af5f5c5c9a9beea1b_3.jpeg","aaa3.jpg");
    
            t1.start();
            t2.start();
            t3.start();
        }
    }
    

    下載的順序不是按t1,t2,t3,開啟多執行緒後而是由系統自動排程分配

② Runnable介面

  • 定義MYRunnable類實現Runable介面

  • 實現run()方法,編寫執行緒執行體

  • 建立執行緒物件,呼叫start()方法啟動執行緒

    public class TestThread3 implements Runnable{
        //重現run方法
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                System.out.println("這是子執行緒"+i);
            }
        }
    
        public static void main(String[] args) {
            //建立runnable介面的實現物件
            TestThread3 testThread3 = new TestThread3()
            //建立執行緒物件——代理
            Thread thread = new Thread(testThread3);
            //開啟執行緒
            thread.start();
    
            for (int i = 0; i < 1000; i++) {
                System.out.println("主執行緒"+i);
            }
        }
    }
    
thread類和runnable介面的區別
多個執行緒同時操作同一個物件
  • 執行緒不安全

    public class TestThread4 implements Runnable{
        private int ticketNum = 10;
    
        @Override
        public void run() {
            while (true) {
    
                if (ticketNum <=0){
                    break;
                }
                //延遲
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //Thread.currentThread().getName()獲取姓名
                System.out.println(Thread.currentThread().getName()+"搶到了第"+ (ticketNum--)+"張票");
            }
        }
    
        public static void main(String[] args) {
            TestThread4 ticket = new TestThread4();
            new Thread(ticket,"小明").start();
            new Thread(ticket,"小紅").start();
            new Thread(ticket,"黃牛").start();
        }
    }
    

龜兔賽跑
//龜兔賽跑
public class TestThread5 implements Runnable {

    private static String winner;//勝利者
    private final int LENGTH = 1000;//賽道長度

    //設定賽道
    @Override
    public void run() {
        for (int i = 0; i <= LENGTH; i++) {
            //判斷比賽是否結束
            boolean flag = this.gameover(i);
            //如果結束,退出迴圈
            if (flag){
                break;
            }

            //比賽進度
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");

            //模擬兔子的狀態
            if (Thread.currentThread().getName().equals("兔子")) {//不能用 == "兔子"
                //模擬兔子跑步比烏龜快
                i += 49;

                //模擬兔子休息
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //判斷比賽是否結束方法
    private boolean gameover(int steps) {
        //已經有勝利者了,返回true
        if (winner != null) {
            return true;
        } else if (steps>=LENGTH){
            winner = Thread.currentThread().getName();
            System.out.println(winner+"贏得了比賽");
            return true;
        }
        //無勝利者,返回false
        return false;
    }

    //主執行緒
    public static void main(String[] args) {
        TestThread5 race = new TestThread5();
        new Thread(race, "兔子").start();
        new Thread(race, "烏龜").start();
    }
}

③ Callable介面

  • 實現Callable介面,需要返回值型別

  • 重現call方法,需要丟擲異常

  • 建立目標物件

  • 建立執行服務

  • 提交執行

  • 獲取結果

  • 關閉服務

    public class TestCallable implements Callable{
        private String url;
        private String name;
    
        public TestCallable(String url, String name) {
            this.url = url;
            this.name = name;
        }
    
        //重寫call方法
        @Override
        public Boolean call() throws Exception {
            this.download(url,name);
            System.out.println("下載檔名為:"+name);
            return true;
        }
    
        //下載方法
        public void download(String url, String name) {
            try {
                FileUtils.copyURLToFile(new URL(url),new File(name));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            TestCallable t1 = new TestCallable("https://04imgmini.eastday.com/mobile/20201124/20201124125422_b97573c574f48a6af5f5c5c9a9beea1b_1.jpeg","bbb1.jpg");
            TestCallable t2 = new TestCallable("https://04imgmini.eastday.com/mobile/20201124/20201124125422_b97573c574f48a6af5f5c5c9a9beea1b_2.jpeg","bbb2.jpg");
            TestCallable t3 = new TestCallable("https://04imgmini.eastday.com/mobile/20201124/20201124125422_b97573c574f48a6af5f5c5c9a9beea1b_3.jpeg","bbb3.jpg");
    
            //建立執行服務
            ExecutorService ser = Executors.newFixedThreadPool(3);
    
            //提交執行
            Future<Boolean> submit1 = ser.submit(t1);
            Future<Boolean> submit2 = ser.submit(t2);
            Future<Boolean> submit3 = ser.submit(t3);
    
            //獲取結果
            Boolean rs1 = submit1.get();
            Boolean rs2 = submit2.get();
            Boolean rs3 = submit3.get();
    
            System.out.println("bbb1.jpg is "+rs1);//可以列印返回值
            System.out.println("bbb2.jpg is "+rs2);
            System.out.println("bbb3.jpg is "+rs3);
    
            //關閉服務
            ser.shutdownNow();
        }
    
    }
    
Callable的好處
  • 可以獲得返回值
  • 可以丟擲異常

2. Lambda表示式

  • 函數語言程式設計
  • 避免匿名內部類定義過多
  • 可以讓程式碼變得簡潔,去掉無意義的程式碼,保留核心邏輯

函式式介面

  • 一個介面只有唯一的一個抽象方法

    由於這個介面中只有這個方法,因此相比匿名內部類,可以實現除了類名,連方法名都可以 省略

    public interface Runnable{
        public abstruct run();
    }
    
  • 推導lamda表示式(逐步簡化)

    關於內部類

    public class TestLambda {
    
        //成員內部類
        class Like2 implements ILike {
            @Override
            public void show() {
                System.out.println("介面實現方式——成員內部類");
            }
        }
    
        //靜態內部類
        static class Like3 implements ILike {
            @Override
            public void show() {
                System.out.println("介面實現方式——靜態內部類");
            }
        }
    
    
        public static void main(String[] args) {
            //1.正常操作 —— 在外部寫介面的實現類
            new Like1().show();
    
            //2. 成員內部類 —— 將實現類寫到內部
            TestLambda testLambda = new TestLambda();
            testLambda.new Like2().show();
    
            //3. 靜態內部類
            new Like3().show();
    
            //4. 區域性內部類
            class Like4 implements ILike {
                @Override
                public void show() {
                    System.out.println("介面實現方式——區域性內部類");
                }
            }
            new Like4().show();
    
    
            //5. 匿名內部類
            new ILike() {
                @Override
                public void show() {
                    System.out.println("介面實現方式——匿名內部類");
                }
            }.show();
    
            //6. lambda簡化
            ILike like = ()->{
                System.out.println("介面的實現方式——lambda表示式");
            };
            like.show();
    
        }
    
    }
    
    //定義一個函式式介面
    interface ILike {
        void show();
    }
    
    //介面實現類
    class Like1 implements ILike {
        @Override
        public void show() {
            System.out.println("介面實現方式——寫實現類(外部)");
        }
    }
    
  • 示例2

    public class TestLambda2 {
        public static void main(String[] args) {
    
            //匿名內部類
            new Meals() {
                @Override
                public void show(String name, String food, int nums) {
                    System.out.println(name+"吃了"+nums+"份"+food);
                }
            }.show("早餐","麵包",3);
    
            //lambda表示式
            Meals meals;
    
            meals = (a,b,c)->{
                System.out.println(a+"吃了"+c+"份"+b);
            };
            meals.show("早餐","麵包",3);
    
            //簡化lambda表示式
            meals = (a,b,c) -> System.out.println(a+"吃了"+c+"份"+b);
            meals.show("早餐","麵包",3);
    
        }
    
    }
    
    interface Meals{
        void show(String name, String food, int nums);
    }
    

    如果方法過載了還滿足lambda只有一個方法的要求嗎?

    • 不行

3. 靜態代理模式

  • 真實物件和代理物件都要實現同一個介面

  • 代理物件要代理真實角色

    不改變原有程式碼,去實現新的功能

    • 靜態代理模式——對方法的增強
    • 裝飾器模式——對物件的增強

好處

  • 代理物件可以做很多真實物件做不了的事

  • 真實物件專注做自己的事

    public class StaticProxy {
        public static void main(String[] args) {
            People you = new People();
            new WeddingCompany(you);
        }
    }
    
    interface Merry{
        void merry();
    }
    
    //你——真實物件
    class People implements Merry{
        @Override
        public void merry() {
            System.out.println("我終於結婚了,超開心TAT");
        }
    }
    
    //婚慶公司——代理
    class WeddingCompany implements Merry{
        private Merry customer;
    
        public WeddingCompany(Merry customer) {
            this.customer = customer;
            this.merry();
        }
    
        @Override
        public void merry() {
            berfore();
            customer.merry();
            after();
        }
    
        private void berfore() {
            System.out.println("結婚前,佈置婚禮");
        }
    
        private void after() {
            System.out.println("結婚後,收取尾款");
        }
    }
    /*
    結婚前,佈置婚禮
    我終於結婚了,超開心TAT
    結婚後,收取尾款
    */
    
  • 與多執行緒建立類比

    //靜態代理模式
    new WeddingCompany(new People()).merry();
    //執行緒建立也構成靜態代理的要求
    new Thread( ()->System.out.println("love")).start();
    
    • 真實物件和代理物件都要實現同一個介面

      Thread 實現 Runnable介面

      lambda表示式為一個匿名的實現類也是實現 Runnable介面

    • 代理物件要代理真實角色

      Thread真實代理lambda表示式的匿名類

三、執行緒狀態

1.執行緒的五種狀態

2. 如何停止執行緒

public class TestStop implements Runnable{
    boolean flag = true;

    @Override
    public void run() {
        //子執行緒就兩條語句,當while執行完,子執行緒就結束了,但while(true)為無限迴圈,也就是說子執行緒只有在flag變為false的時候才會停止
        int i = 0;
        while (flag) {
                System.out.println("*****************子執行緒跑了"+i++);
        }
    }

    //停止執行緒
    void stop() {
        flag = false;
        System.out.println("**************子執行緒停止了");
    }

    public static void main(String[] args) {
        TestStop tt = new TestStop();
        new Thread(tt).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println("主執行緒跑了"+i);
            //主執行緒跑到800的時候把flag變為false——停止子執行緒
            if (i==800) {
                tt.stop();
            }
        }

    }
}

3. sleep()

  • 模擬網路延遲——放大問題的發生行

    public class TestThread4 implements Runnable{
        private int ticketNum = 10;
    
        @Override
        public void run() {
            while (true) {
    
                if (ticketNum <=0){
                    break;
                }
    
                try {
                    //模擬網路延遲——放大問題的發生行,可能列印負數,這個執行緒本身是不安全的
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"搶到了第"+ (ticketNum--)+"張票");
            }
        }
    
        public static void main(String[] args) {
            TestThread4 ticket = new TestThread4();
            new Thread(ticket,"小明").start();
            new Thread(ticket,"小紅").start();
            new Thread(ticket,"黃牛").start();
        }
    }
    
  • 倒計時

    //倒計時
    public class TestSleep {
        public static void main(String[] args) {
            for (int i = 10; i > 0; i--) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(i);
            }
        }
    }
    /*
    10
    9
    8
    ...
    1
    */
    
  • 系統時間

    public class TestSleep2 {
        public static void main(String[] args) {
            //系統時間
            Date date;
    
            while (true) {
                try {
                    date = new Date(System.currentTimeMillis());
                    Thread.sleep(1000);
                    System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
            }
        }
    }
    /*
    21:32:09
    21:32:10
    21:32:11
    21:32:12
    ...
    */
    

4. yield()

public class TestYield {
    public static void main(String[] args) {
        new Thread(new ThreadYield(),"執行緒1").start();
        new Thread(new ThreadYield(),"執行緒2").start();
    }
}

class ThreadYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"執行中");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"已結束");
    }
}
/*
執行緒1執行中
執行緒2執行中
執行緒2已結束
執行緒1已結束
*/

5. join()

  • 合併執行緒,待此執行緒執行完後,再執行其他執行緒,其他執行緒阻塞

  • 可以想象成插隊

    public class TestJoin {
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(() -> {
                for (int i = 0; i < 1000; i++) {
                    System.out.println("子執行緒join後就是vip執行緒了"+i);
                }
            });
            t1.start();
    
            for (int i = 0; i < 500; i++) {
                System.out.println("這是main執行緒"+i);
                
                if (i==400) {
                    t1.join();
                }
                
            }
        }
    
    }
    

    開始時,兩個執行緒交替進行,

    但到主執行緒i=400開始,子執行緒的優先順序變高,主執行緒開始等待,子執行緒執行完後才開始執行主執行緒

6. 執行緒的狀態觀測

getState()

  • 新生 new

  • 就緒

  • 執行 Runnable

    • 阻塞 Block
  • 死亡 Dead

    public class TestState{
    
        //觀察子執行緒
        public static void main(String[] args) {
            //1.新生 2.就緒
            Thread t1 = new Thread(()->{
                try {
                    //4.阻塞
                    Thread.sleep(1000);
                } catch (InterruptedExc eption e) {
                    e.printStackTrace();
                }
    
                //5.執行完這句話--->死亡
                System.out.println("lsat sentence");
            });
            System.out.println(t1.getState());//觀察狀態
    
            //3.啟動
            t1.start();
            System.out.println(t1.getState());
    
            //啟動之後
            while (t1.getState() != Thread.State.TERMINATED) {
                //只要子執行緒不終止,在主執行緒中就不停檢測子執行緒狀態
                try {
                    Thread.sleep(100);
                    System.out.println(t1.getState());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
        }
    }
    

7. 執行緒的優先順序

getPriority()

setPriority(int x)

    public static void main(String[] args) {
        //檢視主執行緒優先順序
        System.out.println(Thread.currentThread().getName() + "優先順序為" + Thread.currentThread().getPriority());

        //建立執行緒
        Thread t1 = new Thread(() -> System.out.println(Thread.currentThread().getName() + "優先順序為" + Thread.currentThread().getPriority()));
        Thread t2 = new Thread(() -> System.out.println(Thread.currentThread().getName() + "優先順序為" + Thread.currentThread().getPriority()));
        Thread t3 = new Thread(() -> System.out.println(Thread.currentThread().getName() + "優先順序為" + Thread.currentThread().getPriority()));
        Thread t4 = new Thread(() -> System.out.println(Thread.currentThread().getName() + "優先順序為" + Thread.currentThread().getPriority()));


        //設定優先順序
        t1.setPriority(7);
        t2.setPriority(3);
        t3.setPriority(Thread.MAX_PRIORITY);
        t4.setPriority(1);

        //啟動執行緒
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
/*
main優先順序為5
Thread-2優先順序為10
Thread-0優先順序為6
Thread-1優先順序為3
Thread-3優先順序為1
*/
  • 效能倒置

    多跑幾次,輸出結果也可能是這樣,因為設定優先順序並不代表一定優先執行,而是優先執行的概率大,(和yield()一樣,重新排程執行緒)具體還是看CPU排程,人為無法干預

    /*
    main優先順序為5
    Thread-0優先順序為6
    Thread-2優先順序為10
    Thread-1優先順序為3
    Thread-3優先順序為1
    */
    

8. 守護執行緒

  • 執行緒分為使用者執行緒守護執行緒

  • 虛擬機器必須確保使用者執行緒執行完畢

  • 虛擬機器不用等待守護執行緒執行完畢

    • 如後臺記錄操作日誌、監控記憶體、垃圾回收等待
    public class TestDeamon {
        public static void main(String[] args) {
            //執行緒1——輸出五秒系統時間
            new Thread(()->{
                for (int i = 0; i < 5; i++) {
                    Date date = new Date(System.currentTimeMillis());
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                    System.out.println(sdf.format(date));
                }
    
                System.out.println("==Goodbye==");
            }).start();
    
            //執行緒2——守護執行緒
            Thread t2 = new Thread(() -> {
                while (true) {
                    System.out.println("==守護執行緒==");
                }
            });
            t2.setDaemon(true);//執行緒預設false,true後變為守護執行緒
            t2.start();
        }
    }
    /*
    ==守護執行緒==
    ==守護執行緒==
    15:46:49
    ==Goodbye==
    ==守護執行緒==
    ==守護執行緒==
    ==守護執行緒==
    */
    

    執行緒2為while死迴圈,但執行緒1執行完,程式依舊結束了,因為虛擬機器不用等待守護執行緒執行完畢

四、執行緒同步(重點)

1. 執行緒同步機制

多個執行緒訪問同一個物件的問題——併發問題

佇列+鎖

解決執行緒的安全性

鎖提高安全性的同時,也會降低效能

2. 為什麼執行緒是不安全的

  • 買票案例

    public class Ticket {
    
        public static void main(String[] args) {
            TicketSale station = new TicketSale();
            new Thread(station, "小明").start();
            new Thread(station, "小紅").start();
            new Thread(station, "黃牛").start();
    
    
        }
    }
    
    class TicketSale implements Runnable{
        private int ticketNums = 10;
        private boolean flag = true;
    
        @Override
        public void run() {
            //買票
            while (flag) {
                if (ticketNums<=0){
                    flag = false;
                    return;//到0就退出迴圈,不執行buyTicket();
                }
                buyTicket();
    /*
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    */
            }
        }
    
        //購票方法
        private void buyTicket (){
            System.out.println(Thread.currentThread().getName()+"搶到了第"+(ticketNums--)+"張票");
        }
    }
    /*
    小明搶到了第10張票
    黃牛搶到了第8張票
    小紅搶到了第9張票
    小明搶到了第6張票
    黃牛搶到了第7張票
    小明搶到了第4張票
    小紅搶到了第5張票
    小明搶到了第2張票
    黃牛搶到了第3張票
    小紅搶到了第1張票...*/
    

    這個sleep放buy方法裡,會導致第一個執行緒在run裡不斷呼叫buy,直接買完所有的票

    放buy外面,sleep阻塞,下一個執行緒就有機會買到了

    sleep方法,放大問題的發生性

    /*
    黃牛搶到了第10張票
    小明搶到了第9張票
    小紅搶到了第10張票
    小紅搶到了第8張票
    小明搶到了第7張票
    黃牛搶到了第6張票...*/
    

    可以看見,黃牛,小紅都搶到了第10張票——即表明執行緒不安全

  • 銀行取錢

    public class BankTest {
        public static void main(String[] args) {
            System.out.println("=======小明夫妻共有5000元存款=======");
            Account account = new Account("存款", 5000);
            new Thread(new Drawing(account, 100), "小明").start();
            new Thread(new Drawing(account, 5000), "妻子").start();
    
        }
    }
    
    //賬戶
    class Account{
        private String name;//賬戶名
        private int money;//存款
    
        public Account(String name,int money) {
            this.name = name;
            this.money = money;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getMoney() {
            return money;
        }
    
        public void setMoney(int money) {
            this.money = money;
        }
    }
    
    //銀行取款
    class Drawing implements Runnable {
        Account account;//賬戶
        int withdraw;//取現
        int cash;//現金
    
        public Drawing(Account account, int withdraw) {
            this.account = account;
            this.withdraw = withdraw;
        }
    
        @Override
        public void run() {
    
            //如果沒有錢退出
            if (account.getMoney() - withdraw <0) {
                System.out.println("存款只有"+account.getMoney()+"取不了"+ withdraw +"元");
                return;
            }
    
            //sleep放大問題的發生性
            //小明和妻子兩個執行緒都在這等待1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            account.setMoney(account.getMoney() - withdraw); //卡內餘額
            cash += withdraw;//現金
    
    
            System.out.println(Thread.currentThread().getName()+"取走了"+withdraw+"元");
            System.out.println(account.getName()+"餘額為"+account.getMoney()+"元");
            System.out.println(Thread.currentThread().getName()+"手中的錢"+cash+"元");
    
        }
    }
    /*
    =======小明夫妻共有5000元存款=======
    妻子取走了5000元
    存款餘額為0元
    妻子手中的錢5000元
    小明取走了100元
    存款餘額為-100元
    小明手中的錢100元
    */
    

    取錢前,小明和妻子等待了1秒,同時操作1個物件,因此都能取出錢

  • list案例

    public class ListTest {
        public static void main(String[] args) {
            List list = new ArrayList<>();
    
            for (int i = 0; i < 100000; i++) {
                new Thread(()->{
                    list.add(Thread.currentThread().getName());
                }).start();
            }
    
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            System.out.println(list.size());
    
        }
    }
    //99973
    

    99973而不是預想的100000,等待了100ms,同時新增1個物件,資料覆蓋,因此執行緒也是不安全的

3. 如何解決執行緒不安全

對屬性的保護——private,寫set/get方法

同步方法

實現原理:佇列與鎖

  • synchronized方法
  • synchronized塊
  • 但也有弊端

    • 不是物件所有內容都需要同步的

    • 修改部分需要同步,而只讀部分不需要同步,浪費資源

同步塊

  • 買票案例

        private synchronized void buyTicket (){
            System.out.println(Thread.currentThread().getName()+"搶到了第"+(ticketNums--)+"張票");
        }
    }
    /*
    小明搶到了第10張票
    小紅搶到了第9張票
    黃牛搶到了第8張票
    小紅搶到了第7張票
    小明搶到了第6張票
    黃牛搶到了第5張票
    小紅搶到了第4張票
    小明搶到了第3張票
    黃牛搶到了第2張票
    小紅搶到了第1張票
    */
    
  • 銀行案例

    @Override
    public void run() {
    
        synchronized (account) {
            //如果沒有錢退出
            if (account.getMoney() - withdraw <0) {
                System.out.println("存款只有"+account.getMoney()+"取不了"+ withdraw +"元");
                return;
            }
    
            //sleep放大問題的發生性
            //小明和妻子兩個執行緒都在這等待1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            account.setMoney(account.getMoney() - withdraw); //卡內餘額
            cash += withdraw;//現金
    
            System.out.println(Thread.currentThread().getName()+"取走了"+withdraw+"元");
            System.out.println(account.getName()+"餘額為"+account.getMoney()+"元");
            System.out.println(Thread.currentThread().getName()+"手中的錢"+cash+"元");
        }
    }
    /*
    =======小明夫妻共有5000元存款=======
    小明取走了100元
    存款餘額為4900元
    小明手中的錢100元
    存款只有4900取不了5000元
    */
    
  • list案例

    for (int i = 0; i < 100000; i++) {
        new Thread(() -> {
            synchronized (list) {
                list.add(Thread.currentThread().getName());
            }
        }).start();
    }
    //100000
    
  • JUC

    public class TestJUC {
        public static void main(String[] args) {
            //安全型別的集合
            CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
            for (int i = 0; i < 10000; i++) {
                new Thread(()-> list.add(Thread.currentThread().getName())).start();
            }
    
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            System.out.println(list.size());
        }
    }
    //10000
    

    transient——臨時的

    volatile——不可被序列化

死鎖

public class DeadLock {
    public static void main(String[] args) {
        System.out.println("0=口紅,1=鏡子");
        new MyMakeup("小明",0).start();
        new MyMakeup("小紅",1).start();
    }
}

class Mirror {}

class Lipstick {}


class MyMakeup extends Thread {
    //資源
    static Mirror mirror = new Mirror();
    static Lipstick lipstick =  new Lipstick();

    //人物、選擇
    String name;
    int choice;

    public MyMakeup(String name, int choice) {
        super(name);
        this.choice = choice;
    }

    @Override
    public void run() {
        //化妝
        makeup();
    }

    //化妝,互相持有對方的鎖——需要拿到對方的資源
    private void makeup() {
        name = Thread.currentThread().getName();

        if (choice==0) {
            //獲得口紅
            synchronized (lipstick){
                System.out.println(name+"拿到了口紅");
                //使用了1秒
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //獲得鏡子
                synchronized (mirror) {
                    System.out.println(name+"拿到了鏡子");
                }
            }
        } else {
            //獲得鏡子
            synchronized (mirror) {
                System.out.println(name+"拿到了鏡子");
                ////使用了1秒
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //獲得口紅
                synchronized (lipstick) {
                    System.out.println(name+"拿到了口紅");
                }
            }
         }
    }
}
/*
0=口紅,1=鏡子
小明拿到了口紅
小紅拿到了鏡子
*/

小明先拿到口紅,小紅先拿到鏡子

但都卡住了,拿不到另一樣東西

小明鎖了口紅時,要拿鏡子這個資源,但鏡子被小紅鎖了,要等待小紅執行完解鎖

小紅鎖了鏡子時,要拿口紅這個資源,但口紅被小明鎖了,要等待小明執行完解鎖,這樣就死鎖了

  • 解決方案,將鎖提出來
private void makeup() {
    name = Thread.currentThread().getName();

    if (choice==0) {
        //獲得口紅
        synchronized (lipstick){
            System.out.println(name+"拿到了口紅");
            //使用了1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name+"放回了口紅");

        }

        //獲得鏡子
        synchronized (mirror) {
            System.out.println(name+"拿到了鏡子");
        }
        
    } else {
        //獲得鏡子
        synchronized (mirror) {
            System.out.println(name+"拿到了鏡子");
            ////使用了1秒
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name+"放回了鏡子");
        }

        //獲得口紅
        synchronized (lipstick) {
            System.out.println(name+"拿到了口紅");
        }

    }
}
/*
0=口紅,1=鏡子
小紅拿到了鏡子
小明拿到了口紅
小明放回了口紅
小明拿到了鏡子
小紅放回了鏡子
小紅拿到了口紅
*/

LOCK

ReentrantLock類——可重入鎖

public class TestLock {
    public static void main(String[] args) {

        Test test = new Test();

        new Thread(test,"執行緒1").start();
        new Thread(test,"執行緒2").start();
        new Thread(test,"執行緒3").start();

    }
}

class Test implements Runnable {

    ReentrantLock lock = new ReentrantLock();//定義Lock鎖
    int num = 10;

    @Override
    public void run() {
        while(true) {
            try {
                lock.lock();//加鎖
                if (num>0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+" :"+num--);
                } else {
                    break;
                }
            } finally {
                lock.unlock();//解鎖
            }
        }
    }
}

這是lock鎖this這個物件,但如果要像Synchronized(特定物件),又該如何用lock實現

五、執行緒通訊問題

生產者消費者問題

1. 管程法

public class Demo02 {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();//緩衝區      
        new Productor(buffer).start(); //生產者
        new Consumer(buffer).start(); //消費者
    }

}

//產品
class Product {
    int id;

    public Product(int id) {
        this.id = id;
    }
}

//緩衝區
class Buffer {
    //1. 定義一個容器——用於存放產品
    Product[] container = new Product[10];//可以存10個
    int count = 0;//產品個數

    //2. 生產者把東西放到緩衝區的方法
    synchronized int push (Product product) {
        //如果容器滿了,就通知生產者停止生產
        if (count>= container.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果容器沒滿,生產者一直會生產
            //將生產的產品存入緩衝區
        container[count++] = product;

        //通知消費者消費
        this.notifyAll();

        return count;
    }

    //3. 消費者把東西從到緩衝區取出的方法
    synchronized Product pop() {

        //如果容器空了,通知消費者等待
        if (count <= 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果容器沒滿,通知消費者消費
            //將產品從緩衝區取出
        Product takeout = container[--count];
        System.out.println("            ===取出"+takeout.id+"號===");

        //通知生產者生產
        this.notifyAll();

        return takeout;
    }

}

//生產者
class Productor extends Thread{
    Buffer buffer;

    public Productor(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        int id = 1;

        while(true) {
            //生產、把產品放到緩衝區
            Product product = new Product(id);
            System.out.println("生產了"+id+"號產品\n"+"===投放"+(id++)+"號===\n===倉庫共有"+buffer.push(product)+"件產品==========");

            if (id>=100) {
                break;
            }
        }
    }
}

//消費者
class Consumer extends Thread{
    Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        int count = 1;
        while(true){
            //這裡buffer.pop()返回的是一個product物件所有能用.id

            System.out.println("            "+buffer.pop().id+"號完成消費");

            if (count>=100) {
                return;
            }
        }

    }
}
  • 輸出日誌

    生產了1號產品
    ===投放1號===
    ===倉庫共有1件產品==========
    生產了2號產品
    ===投放2號===
    ===倉庫共有2件產品==========
    生產了3號產品
    ===投放3號===
    ===倉庫共有3件產品==========
    生產了4號產品
    ===投放4號===
    ===倉庫共有4件產品==========
    生產了5號產品
    ===投放5號===
    ===倉庫共有5件產品==========
    生產了6號產品
    ===投放6號===
    ===倉庫共有6件產品==========
    生產了7號產品
    ===投放7號===
    ===倉庫共有7件產品==========
    生產了8號產品
    ===投放8號===
    ===倉庫共有8件產品==========
    生產了9號產品
    ===投放9號===
    ===倉庫共有9件產品==========
    生產了10號產品
    ===投放10號===
    ===倉庫共有10件產品==========
                ===取出10號===
                10號完成消費
    生產了11號產品
    ===投放11號===
    ===倉庫共有10件產品==========
                ===取出11號===
                11號完成消費
                ===取出12號===
                12號完成消費
                ===取出9號===
                9號完成消費
                ===取出8號===
                8號完成消費
                ===取出7號===
                7號完成消費
                ===取出6號===
                6號完成消費
                ===取出5號===
                5號完成消費
                ===取出4號===
                4號完成消費
                ===取出3號===
                3號完成消費
                ===取出2號===
                2號完成消費
                ===取出1號===
                1號完成消費
    生產了12號產品
    ===投放12號===
    ===倉庫共有10件產品==========
    生產了13號產品
    ===投放13號===
    ===倉庫共有1件產品==========
    生產了14號產品
    ===投放14號===
    ===倉庫共有2件產品==========
                ===取出14號===
                14號完成消費
                ===取出13號===
                13號完成消費
    生產了15號產品
    ===投放15號===
    ===倉庫共有1件產品==========
    ......
    
  • 關於wait

2. 訊號燈法

//訊號燈法
public class Demo03 {
    public static void main(String[] args) {

        TvShow tvShow = new TvShow();
        new Actors(tvShow).start();
        new Audiences(tvShow).start();
    }
}
//演員——生產者
class Actors extends Thread {
    TvShow tvShow;

    public Actors(TvShow tvShow) {
        super("演員");
        this.tvShow = tvShow;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0) {
                tvShow.transcribe("快樂大本營");
            } else {
                tvShow.transcribe("抖音");
            }

        }
    }
}

//觀眾——消費者
class Audiences extends Thread {
    TvShow tvShow;

    public Audiences(TvShow tvShow) {
        super("觀眾");
        this.tvShow = tvShow;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0) {
                tvShow.watch("快樂大本營");
            } else {
                tvShow.watch("抖音");
            }
        }
    }
}

//節目——產品————由於只兩種種狀態,所以不需要緩衝區
class TvShow {
    boolean flag = true;
    String programName;

    //演員錄製,觀眾等待
    synchronized void transcribe (String programName){
        //false通知演員休息
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //true通知演員表演
        System.out.println(Thread.currentThread().getName()+"錄製了"+programName);

        this.notifyAll();//演員表演完,通知等待的觀眾再觀看
        flag = !flag;
    }

    //觀眾觀看,演員休息
    synchronized void watch(String programName) {

        //ture通知觀眾等待
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //false通知觀眾收看
        System.out.println(Thread.currentThread().getName()+"收看了"+programName);

        this.notifyAll();//觀眾受看完,通知休息的演員再錄製
        flag = !flag;
    }

}

六、高階主題

1. 執行緒池

  • 提前再執行緒池建立好一些執行緒,使用時呼叫,結束時放回執行緒池
  • 便於重複利用
  • ExecutorService——執行緒池
  • Executors——建立執行緒池的工具類

2.用Runnable實現執行緒池

public class executorService {
    public static void main(String[] args) {
        //開啟執行緒池
        ExecutorService service = Executors.newFixedThreadPool(10);
        
        service.execute(new Test());//execute(),提交runnable實現的執行緒
        service.execute(new Test());
        service.execute(new Test());
        service.execute(new Test());
        service.submit(new Test());//通用的提交執行緒方法
        service.submit(new Test());
        service.submit(new Test());

        //關閉執行緒池
        service.shutdown();
    }
}

class Test implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"helloworld");
    }
}

七、總結

1. 建立執行緒的三種方法

public class Demo01 {
    public static void main(String[] args) {
        //Thread
        new Thread1().start();
        //Runnable
        new Thread(new Thread2()).start();
        //Callable
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new Thread3());
        new Thread(futureTask);//futrueTask繼承了Runnable介面

        //執行緒池
        ExecutorService service = Executors.newFixedThreadPool(3);
        service.submit(new Thread1());//提交
        service.submit(new Thread2());
        service.submit(new Thread3());
        service.shutdown();//關閉執行緒池
    }
}

class Thread1 extends Thread {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Thread實現多執行緒");
    }
}

class Thread2 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Runnable實現多執行緒");
    }
}

class Thread3 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"Callable實現多執行緒");
        return 100;
    }
}