1. 程式人生 > 其它 >JAVA學習-多執行緒

JAVA學習-多執行緒

多執行緒

Thread

  • 自定義執行緒類繼承Thread類
  • 重寫run()方法,編寫執行緒執行體
  • 建立執行緒物件,呼叫start()方法啟動執行緒

注意:如果呼叫run()方法,則只有主執行緒一條執行路徑,但呼叫start()方法,則多條執行路徑,主執行緒和子執行緒並行交替執行

package com.myThread.demo01;

public class Demo01 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        for (int i = 0; i < 10000; i++) {
            System.out.println("我是主執行緒--"+i);
        }
    }
}
///////////////////////////
package com.myThread.demo01;

public class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println("我是子執行緒--"+i);
        }
    }
}

**執行緒的執行由CPU決定 **

網路圖片下載

需要用到commons io包 百度下載二進位制檔案 然後複製貼上到idea新建一個lib包裡即可

package com.myThread.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class Demo01 {
    public static void main(String[] args) {
        MyThread myThread1 = new MyThread("https://img2022.cnblogs.com/blog/1755845/202202/1755845-20220206182923194-2117509516.png","4.jpg");
        MyThread myThread2 = new MyThread("https://img2022.cnblogs.com/blog/1755845/202203/1755845-20220303112203654-338817152.png","5.jpg");
        MyThread myThread3 = new MyThread("https://img2022.cnblogs.com/blog/1755845/202202/1755845-20220223223043340-1183125272.png","6.jpg");
        myThread1.start();
        myThread2.start();
        myThread3.start();
    }
}
//子執行緒寫下載,實現多執行緒下載資源
class MyThread extends Thread{
    private String myUrl = null;
    private String myname = null;

    public MyThread(String url,String name) {
        this.myname = name;
        this.myUrl = url;
    }

    @Override
    public void run() {
        WebDownload webDownload = new WebDownload();
        webDownload.download(myUrl,myname);
        System.out.println("下載好了"+myname);
    }
}
//下載器
class WebDownload{
    public void download(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("下載器方法出現異常!");
        } finally {
        }

    }
}

再次證明了執行緒是由CUP分配的,人為無法干預

Runnable介面

建立執行緒方式2:實現runnable介面,重寫run方法,執行執行緒需要丟入物件

package com.myThread.demo03;

public class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("我在看書--"+i);
        }
    }
}
////////////////////////
package com.myThread.demo03;

public class Demo01 {
    public static void main(String[] args) {
        new Thread(new MyRunnable()).start();//這裡new一個Thread 然後把實現runnable介面的物件丟進去
        for (int i = 0; i < 2000; i++) {
            System.out.println("我在玩手機--"+i);
        }


    }
}

最好使用runnable介面實現多執行緒,避免單繼承侷限性,靈活方便,方便同一個物件被多個執行緒使用

初識併發問題

package com.myThread.demo04;

public class MyTicket implements Runnable{
    private int ticketNums = 1;

    @Override
    public void run() {
        while (true){
            if (ticketNums>=20){
                break;
            }
            try {
                Thread.sleep(200);//模擬延時
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
            }
            //Thread.currentThread().getName() 可以拿到當前執行緒的名字 這裡三執行緒同用一個物件 
            System.out.println(Thread.currentThread().getName()+"--搶到了第"+ticketNums+++"張票!");
        }
    }
}
////////////////////
package com.myThread.demo04;

public class Demo01 {
    public static void main(String[] args) {
        MyTicket ticket = new MyTicket();//物件new一個就行了
        //三執行緒同用一個物件
        new Thread(ticket,"張三").start();
        new Thread(ticket,"李四").start();
        new Thread(ticket,"王五").start();

    }
}

執行結果:

李四和王五都搶到了第二張票,說明執行緒不安全,出現了資料紊亂。這就是執行緒併發出現的問題。

龜兔賽跑

要求跑道100,兔子烏龜一起跑,但兔子要睡覺,烏龜取得勝利

package com.myThread.demo05;

public class Race implements Runnable{
    private int steps = 1;
    private static String winner;
    @Override
    public void run() {
        while (true){

            if (Thread.currentThread().getName().equals("兔子") && steps%10 == 0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                }
            }

            if (theWinner(steps)){//小細節,判斷要放在兔子休眠後,可以避免兔子在接受比賽後又多跑一步
                break;
            }

            System.out.println(Thread.currentThread().getName()+"--已經跑了"+steps+++"步");


        }
    }
    public boolean theWinner(int steps){
        if (winner != null){
            return true;//這句話必須寫,要不然兔子或烏龜一個跑完了另一個執行緒不會停止!!
        }
        else if (steps>=100 && winner == null){
            winner = Thread.currentThread().getName();
            System.out.println(winner+"獲得了勝利!");
            return true;
        }
        return false;

    }
}
////////////////////////////
package com.myThread.demo05;

public class Demo01 {
    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"烏龜").start();
        new Thread(race,"兔子").start();
    }
}

Callable介面

不是很明白,以後再來!

靜態代理

真實物件與代理物件實現同一個介面,代理物件要代理真實物件。真實物件通過構造器傳給代理物件,代理物件就可以不僅完成真實物件的方法,還可以做很多真實物件沒有做的事情,真實物件只需要專注自己的事情。

Lambda表示式

Lambda可以簡化程式碼,但注意:

  • 介面必須是函式式介面,也就是介面只能存在一種帶實現的方法
  • 方法內程式碼如果只有一行,可以簡化不寫花括號,如果有多行,必須使用程式碼塊包裹,也就是花括號
  • 介面待實現方法含參,可以去掉引數型別,多個引數也能去掉引數型別,要去掉就都去掉,必須加上括號(引數只有一個,括號也能去掉)
  • 格式為 介面 名字 = (引數) -> {程式碼};
package com.myThread.demo06;

public class Demo01 {
    public static void main(String[] args) {
        Marry marry = null;
        marry = ()-> System.out.println("lalla");
        marry.makeMarry();
    }
}
interface Marry{
    void makeMarry();
}

執行緒停止

執行緒停止,自己在while迴圈裡用一個flag標誌位來控制

.sleep

執行緒休眠

利用休眠做一個定時器,每一秒重新整理一次時間

package com.myThread.demo07;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Demo01 {
    public static void main(String[] args) {
        Runnable runnable = null;
        runnable = ()->{
            while (true){
                LocalDateTime localDateTime = LocalDateTime.now();//獲取時間
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");//調整格式
                System.out.println(dateTimeFormatter.format(localDateTime));//按照格式輸出時間
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                }

            }
        };
        new Thread(runnable).start();
    }
}

.yield

執行緒禮讓

  • 禮讓執行緒,讓當前正在執行的執行緒暫停,但不阻塞
  • 將執行緒從執行狀態轉為就緒狀態
  • 讓cpu重新排程,禮讓不一定成功!看cpu心情

.join

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

可以理解為插隊

package com.myThread.demo08;

public class Demo08 implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("我是vip--"+i);
        }
    }

    public static void main(String[] args) {
        Demo08 demo08 = new Demo08();
        Thread thread = new Thread(demo08);
        thread.start();

        for (int i = 0; i < 2000; i++) {
            System.out.println("我是主執行緒--"+i);
            if (i == 1000){
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                }
            }
        }

    }
}

由上,讓執行緒插隊,等主執行緒1000時插隊,但主執行緒沒到1000時也會跑,完全聽從cpu排程,但一旦主執行緒到達1000就強行插隊,知道執行緒跑完再開始主執行緒

觀測執行緒

Thread.State state = thread.getState();
System.out.println(state);

執行緒優先順序

**set priority() get priority() **

守護執行緒

set daemon()

守護執行緒會隨著使用者執行緒結束,虛擬機器停止就停止了。虛擬機器不會等待守護執行緒的執行。

package com.myThread.demo09;

public class Demo01 {
    public static void main(String[] args) {
        You you = new You();
        God god = new God();
        new Thread(you).start();
        Thread thread = new Thread(god);
        thread.setDaemon(true);
        thread.start();
    }
}

class You implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i < 36500; i++) {
            System.out.println("活著的第--"+i+"天");
        }
        System.out.println("=====goodbye,world!=====");
    }
}
class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("老天爺看著你");
        }
    }
}

上面的god執行緒雖然用了while(true)迴圈,但程式也會隨著使用者執行緒的停止然後虛擬機器的停止而停止。(虛擬機器的停止需要一小點時間)

不安全問題

銀行取錢的不安全問題,程式碼稍微有點不理想,將就吧,也確實出現了執行緒不安全

package com.unsafeDemo.demo01;
//銀行取錢執行緒不安全
public class Demo01 {
    public static void main(String[] args) {
        Account account = new Account(100,"全部家當");
        Bank bank = new Bank(account,50,"小明");
        Bank bank1 = new Bank(account,70,"小紅");
        new Thread(bank).start();
        new Thread(bank1).start();
    }
}
class Account {
    int money;
    String name;
    public Account(int money, String name){
        this.money = money;
        this.name = name;

    }
}

class Bank implements Runnable{
    Account account ;
    private int drawingMoney;
    private String name;
    public Bank(Account account, int drawingMoney, String name){

       this.drawingMoney = drawingMoney;
       this.account = account;
       this.name = name;
    }
    public void drawingMoney(){
        account.money = account.money - drawingMoney;
        System.out.println(this.name+"取了"+drawingMoney);
        System.out.println("餘額為"+account.money);
    }

    @Override
    public void run() {
        if (drawingMoney > account.money){
            System.out.println("沒錢了,取雞毛");
            return;
        }
        try {
            Thread.sleep(100);//利用延遲放大問題
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        drawingMoney();


    }
}

同步塊

synchronized (Obj){}

Obj可以是任何物件,要填入需要被鎖的物件,也就是有變化的物件,然後再將變化過程的程式碼放在這個同步塊裡面。

Lock

可顯示話的鎖,一般使用ReentrantLock類(可重入鎖)

先複習不加鎖:

package com.unsafeDemo.demo02;

public class Demo02 {
    public static void main(String[] args) {
        BuyTicks ticks = new BuyTicks();
        Thread t1 = new Thread(ticks,"我");
        Thread t2 = new Thread(ticks,"你");
        Thread t3 = new Thread(ticks,"他");
        t1.start();
        t2.start();
        t3.start();
    }
}
class BuyTicks implements Runnable{
    private int ticks = 10;
    boolean flag = true;

    @Override
    public void run() {
        while(flag) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (ticks > 0) {
                System.out.println(Thread.currentThread().getName() + "搶到了第" + ticks-- + "票");
            }else {
                flag = false;
            }
        }
    }
}

加鎖程式碼:

package com.unsafeDemo.demo02;

import java.util.concurrent.locks.ReentrantLock;

public class Demo02 {
    public static void main(String[] args) {
        BuyTicks ticks = new BuyTicks();
        Thread t1 = new Thread(ticks,"我");
        Thread t2 = new Thread(ticks,"你");
        Thread t3 = new Thread(ticks,"他");
        t1.start();
        t2.start();
        t3.start();
    }
}
class BuyTicks implements Runnable{
    private int ticks = 10;
    boolean flag = true;
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {

        try {
            lock.lock();
            while(flag) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (ticks > 0) {
                    System.out.println(Thread.currentThread().getName() + "搶到了第" + ticks-- + "票");
                }else {
                    flag = false;
                }
            }
        } finally {
            lock.unlock();

        }
    }
}

注意,new ReentrantLock的時候給他加修飾符private final,不懂,但是照葫蘆畫瓢,然後就是加鎖和解鎖,放在catch-finally裡面,不懂,繼續照葫蘆畫瓢。

生產者消費者

wait() notifyAll() 是隻能寫在synchronized裡面的

package com.myPC.demo03;

public class Demo03 {
    public static void main(String[] args) {
        MyContainer myContainer = new MyContainer();
        new Productor(myContainer).start();
        new Consumer(myContainer).start();

    }
}
class Productor extends Thread{
    MyContainer myContainer;

    public Productor(MyContainer myContainer) {
        this.myContainer = myContainer;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            myContainer.push(new Chicken(i));
            System.out.println("生產了第"+i+"只雞");

        }

    }
}
class Consumer extends Thread{
    MyContainer myContainer;

    public Consumer(MyContainer myContainer) {
        this.myContainer = myContainer;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println("消費了第"+myContainer.del().id+"只雞");
        }


    }

}
class Chicken{
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}
class  MyContainer{
    Chicken[] chickens = new Chicken[10];
    int count = 0;
    public synchronized void push(Chicken chicken){
        while (count >= chickens.length){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        chickens[count] = chicken;
        count++;
        notifyAll();//喚醒所有執行緒,包括沒有雞時停止的消費執行緒

    }

    public synchronized Chicken del(){
        if (count <= 0){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        Chicken chicken = chickens[count];
        notifyAll();//喚醒所有執行緒,包括雞滿了停止的生產執行緒
        return chicken;
    }


}

關於wait() 與 notifyAll() 的思考

package com.myPC.demo04;

import java.util.concurrent.locks.ReentrantLock;

public class Demo04 {
    public static void main(String[] args) {
        abc abc = new abc();
        new Thread(abc,"a").start();
        new Thread(abc,"b").start();
    }

}
class abc implements Runnable{
    int count = 1;
    @Override
    public synchronized void run() {
        for (int i = 0; i < 19; i++) {


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (Thread.currentThread().getName().equals("a") && count%5==0  ){
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("a被喚醒!");
                }
            while (Thread.currentThread().getName().equals("b") && count%4==0 ){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("b被喚醒!");
            }
                System.out.println(Thread.currentThread().getName()+"--得到了"+count);
                count++;
                notifyAll();
            
        }
    }

}

這段程式碼,就是讓ab去獲取數字,一開始,a被cpu指派去獲取,但到a走進while迴圈裡面碰見wait的時候,a停了,這個時候,cpu會直接讓b接進來繼續獲取數字,並且通過notifyAll把a喚醒,a會不會獲取數字看cpu排程,但是一旦b走進while迴圈碰見wait,則會讓a繼續從a停止的wait那裡開始往下走。只要a從休眠狀態被喚醒再被cpu排程,都是繼續從wait那裡開始執行。

訊號燈法

利用一個flag標誌位來解決生產者消費者的問題


執行緒池

ExecutorService:真正的執行緒池介面。常見子類ThreadPoolExecutor

Executors:工具類,執行緒池的工廠類,用於建立並返回不同型別的執行緒池

package com.myPC.demo05;

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

public class Demo05 {
    public static void main(String[] args) {
        //建立一個執行緒池服務
        ExecutorService service = Executors.newFixedThreadPool(3);//引數的意義是執行緒池的大小
        //執行
        service.execute(new MyPool());
        service.execute(new MyPool());
        service.execute(new MyPool());
        //關閉執行緒池
        service.shutdown();

    }
}
class MyPool implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

這裡與Callable有點相似,這是屬於Runnable介面的執行緒池