汽車行業(yè)網(wǎng)站建設方案愛站網(wǎng)關鍵字挖掘
1. 為什么要有多線程?
線程:線程是操作系統(tǒng)能夠進行運算調度的最小單位。它被包含在進程之中,是進程中實際運行單位。
進程:進程是程序的基本執(zhí)行實體。
-
什么是多線程?
有了多線程,我們就可以讓程序同時做多件事情。
- 多線程的作用?
提高效率
- 多線程的應用場景?
只要你想讓多個事件同時運行就需要多線程
比如:軟件中的耗時操作、所有的聊天軟件、所有的服務器。
?
2. 多線程的兩個概念?
并發(fā):在同一時刻,有多個指令在單個 CPU 上交替執(zhí)行
并行:在同一時刻,有多個指令在多個 CPU 上同時執(zhí)行
3. 多線程的實現(xiàn)方式
1. 繼承 Thread 類的方法進行實現(xiàn)2. 實現(xiàn) Runnable 接口的方式進行實現(xiàn)3. 利用 Callable 接口和 Future 接口方式實現(xiàn)
多線程實現(xiàn)方式1-代碼示例:
public class MyThread extends Thread{@Overridepublic void run() {// 線程要執(zhí)行的代碼for (int i = 0; i < 100; i++) {System.out.println(getName() + "hello world");}}
}
public class ThreadDemo {public static void main(String[] args) {/*** 多線程的第一種啟動方式* 1. 自己定義一個類繼承 Thread 類* 2. 重寫 run 方法* 3. 創(chuàng)建子類對象,并啟動線程*/MyThread t1 = new MyThread();MyThread t2 = new MyThread();t1.setName("線程1");t2.setName("線程2");// 開啟線程t1.start();t2.start();}
}
多線程實現(xiàn)方式2-代碼示例:
public class MyRun implements Runnable{@Overridepublic void run() {// 線程要執(zhí)行的代碼for (int i = 0; i < 100; i++) {// 獲取當前線程對象System.out.println(Thread.currentThread().getName() + "hello world");}}
}
public class ThreadDemo {public static void main(String[] args) {/*** 多線程的第二種實現(xiàn)方式* 1. 自己定義一個類實現(xiàn) Runnable 接口* 2. 重寫里面的 run 方法* 3. 創(chuàng)建自己的類的對象。* 4. 創(chuàng)建一個 Thread 類的對象,并開啟多線程*/// 創(chuàng)建 MyRun 對象// 表示多線程要執(zhí)行的任務MyRun mr = new MyRun();// 創(chuàng)建線程對象Thread t1 = new Thread(mr);Thread t2 = new Thread(mr);// 給線程設置名字t1.setName("線程一");t2.setName("線程二");// 開啟線程t1.start();t2.start();}
}
多線程實現(xiàn)方式3-代碼示例:
public class MyCallable implements Callable<Integer> {@Overridepublic Integer call() throws Exception {// 求 1-100 之間的和int sum = 0;for (int i = 0; i <= 100; i++) {sum = sum + i;}return sum;}
}
public class ThreadDemo {public static void main(String[] args) throws ExecutionException, InterruptedException {/*** 多線程第三種實現(xiàn)方式:* 特點:可以獲取到多線程運行的結果** 1. 創(chuàng)建一個類 MyCallable 實現(xiàn) Callable 接口* 2. 重寫 call(是有返回值的,表示多線程運行的結果)* 3. 創(chuàng)建 MyCallable 的對象(表示多線程要執(zhí)行的任務)* 4. 創(chuàng)建 FutureTask 的對象(作用管理多線程運行的結果)* 5. 創(chuàng)建 Thread 類的對象,并啟動(表示線程)*/// 創(chuàng)建 MyCallable 的對象(表示多線程要執(zhí)行的任務)MyCallable mc = new MyCallable();// 創(chuàng)建 FutureTask 的對象(作用管理多線程運行的結果)FutureTask<Integer> ft = new FutureTask<>(mc);// 創(chuàng)建線程的對象Thread t1 = new Thread(ft);// 開啟線程t1.start();// 獲取多線程運行的結果Integer result = ft.get();System.out.println(result);}
}
4. 常見的成員方法
setName && currentThread && sleep
public class MyThread extends Thread{public MyThread() {}public MyThread(String name) {super(name);}@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(getName() + "@" + i);}}
}
public class ThreadDemo {public static void main(String[] args) throws InterruptedException {/*** void setName(String name) 設置線程的名字(構造方法也可以設置名字)* 細節(jié):* 1、如果我們沒有給線程名字,線程也有默認的名字的* 格式:Thread-X(X 序號,從 0 開始的)* 2、如果我們要給線程設置名字,可以用 set 方法進行設置,也可以用構造方法設置** static Thread currentThread() 獲取當前線程對象* 細節(jié):* 當 JVM 虛擬機啟動后,會自動啟動多條線程* 當其中有一條線程就叫做 main 線程* 它的主要作用發(fā)就是調用 main 方法,并執(zhí)行里面的代碼* 在以前,我們寫的所有代碼,其實就是運行在 main 線程當中。* static void sleep(long time) 讓線程休眠指定的時間,單位為毫秒* 細節(jié):* 1、那條線程執(zhí)行到這個方法,那么哪條線程就會停留對應的時間* 2、方法的參數(shù):就表示睡眠的時間,單位毫秒(1秒 = 1000毫秒)* 3、當時間到了之后,線程就會自動醒來,繼續(xù)執(zhí)行下面的其他代碼**///setName/*// 1. 創(chuàng)建線程對象MyThread t1 = new MyThread("飛機");MyThread t2 = new MyThread("坦克");// 2. 開啟線程t1.start();t2.start();*/// 哪條線程執(zhí)行到這個方法,此時獲取的就是哪條線程的鍍錫/*Thread t = Thread.currentThread();String name = t.getName();System.out.println(name); // main*/// sleep/*System.out.println("111111111111111");Thread.sleep(5000);System.out.println("222222222222222");*/}
}
setPriority && getPriority
public class MyRunnable implements Runnable{@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(Thread.currentThread().getName() + "---" +i);}}
}
public class ThreadDemo {public static void main(String[] args) {/*** setPriority(int newPriority) 設置線程的優(yōu)先級* final int getPriority() 獲取線程的優(yōu)先級*/// 創(chuàng)建線程要執(zhí)行的參數(shù)對象MyRunnable mr = new MyRunnable();// 創(chuàng)建線程對象Thread t1 = new Thread(mr, "飛機");Thread t2 = new Thread(mr, "坦克");t1.setPriority(1);t2.setPriority(10);t1.start();t2.start();}
}
守護線程
public class MyThread1 extends Thread{@Overridepublic void run() {for (int i = 0; i < 10; i++) {System.out.println(getName() + "@" + i);}}
}
public class MyThread2 extends Thread{@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(getName() + "@" + i);}}
}
public class ThreadDemo {public static void main(String[] args) {/*** final void setDaemon(boolean on) 設置為守護線程* 細節(jié):* 當其他的非守護線程執(zhí)行完畢之后,守護線程就會陸續(xù)結束* 通俗易懂:* 當女神線程結束了,那么備胎也沒有存在的必要了*/MyThread1 t1 = new MyThread1();MyThread2 t2 = new MyThread2();t1.setName("女神");t2.setName("備胎");// 把第二個線程設置為守護線程(備胎線程)t2.setDaemon(true);t1.start();t2.start();}
}
禮讓線程
public class MyThread extends Thread{@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(getName() + "@" + i);// 表示出讓當前 CPU 的執(zhí)行權,讓出執(zhí)行權的線程也會重新參與搶奪。Thread.yield();}}
}
public class ThreadDemo {public static void main(String[] args) {/*** public static void yield() 出讓線程/禮讓線程*/MyThread t1 = new MyThread();MyThread t2 = new MyThread();t1.setName("飛機");t2.setName("坦克");t1.start();t2.start();}
}
插入線程
public class MyThread extends Thread{@Overridepublic void run() {for (int i = 0; i < 100; i++) {System.out.println(getName() + "@" + i);}}
}
public class ThreadDemo {public static void main(String[] args) throws InterruptedException {/*** public final void join() 插入線程/插隊線程*/MyThread t = new MyThread();t.setName("土豆");t.start();// 把 t 線程插入到當前線程之前。// t:土豆// 當前線程:maint.join();// 執(zhí)行在 main 線程中的方法for (int i = 0; i < 10; i++) {System.out.println("main 線程" + i);}}
}
線程的生命周期
5. 線程安全問題
public class MyThread extends Thread{// static 表示這個類所有的對象都共享 ticketint ticket = 0; // 0 ~ 99@Overridepublic void run() {while (true) {if (ticket < 100) {try {sleep(100);} catch (InterruptedException e) {e.printStackTrace();}ticket++;System.out.println(getName() + "正在賣" + ticket + "張票!!!");} else {break;}}}
}
public class ThreadDemo {public static void main(String[] args) {/*** 需求:* 某電影院目前正在上映國產(chǎn)大片,共 100 張票,而它有 3 個窗口賣票,請設計一個程序模擬該電影院賣票。*/// 創(chuàng)建線程對象MyThread t1 = new MyThread();MyThread t2 = new MyThread();MyThread t3 = new MyThread();// 起名字t1.setName("窗口一");t2.setName("窗口二");t3.setName("窗口三");// 開啟線程t1.start();t2.start();t3.start();}
}
上面的代碼存在以下問題:
- 超賣:線程1、2、3都有可能在同時查看剩余票數(shù)時,都看到還有可賣的票,于是同時執(zhí)行買票操作。
- 賣出相同的票:因為在線程1、2、3都有可能同一時間進行買票操作
同步代碼塊解決線程安全問題
格式:
synchronized (鎖) {操作共享數(shù)據(jù)的代碼
}
特點1:鎖默認打開,有一個線程進去了,鎖會自動關閉
特點2:里面的代碼全部執(zhí)行完畢,線程出來,鎖自動打開
修改之后的線程代碼
public class MyThread extends Thread{// static 表示這個類所有的對象都共享 ticketstatic int ticket = 0; // 0 ~ 99// 加 static 保證 obj 是唯一的。(鎖對象要保證是唯一的)static Object obj = new Object();@Overridepublic void run() {while (true) {// 同步代碼塊synchronized (obj) { // 這里的 obj 也可以替換成 MyThread.class(MyThread 的字節(jié)碼文件),因為 MyThread 的字節(jié)碼文件也是唯一的。 if (ticket < 100) {try {sleep(10);} catch (InterruptedException e) {e.printStackTrace();}ticket++;System.out.println(getName() + "正在賣" + ticket + "張票!!!");} else {break;}}}}
}
注意:鎖要加在 while 循環(huán)的里面,如果加在循環(huán)的外面,某個線程搶到鎖后,會一直執(zhí)行循環(huán)內的代碼,直到這個線程把所有的票買完。因為線程搶到票之后,就算其它線程也搶到票,也只能在循環(huán)鎖外面等著。
同步方法
格式:修飾符 synchronized 返回值類型 方法名(方法參數(shù)) {…}
特點1:同步方法是鎖住方法里面的代碼
特點2:鎖對象不能自己指定
- 非靜態(tài):this
- 靜態(tài):當前類的字節(jié)碼文件對象
StringBuffer 與 StringBuilder 的線程安全區(qū)別:
-
StringBuffer 是線程安全的。因為在 StringBuffer 中有 synchronized 關鍵字。
-
而 StringBuilder 則不是線程安全的。
那對 StringBuffer 和 StringBuilder 我們如何選擇?
- 代碼是單線程的,不涉及多線程、線程安全的問題,那么選擇 StringBuilder 就好了。
- 如果是多線程,設計線程安全問題,那么可以選擇 StringBuffer 。
6. 死鎖
6.1 鎖 lock
-
示例代碼
// 創(chuàng)建鎖對象 Lock lock = new ReentrantLock(); // 設置鎖 lock.lock(); // 釋放鎖 lock.unlock();
-
鎖的應用
public class MyThread extends Thread{static int ticket = 0;// 加 static 使每個線程都用統(tǒng)一把鎖static Lock lock = new ReentrantLock();@Overridepublic void run() {// 1. 循環(huán)while (true) {// 2. 同步代碼塊lock.lock();try {// 3. 判斷if (ticket == 100) {break;} else {// 4. 判斷Thread.sleep(10);ticket++;System.out.println(getName() + "在賣第" + ticket + "張票");}} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}} }
public class ThreadDemo {public static void main(String[] args) {/*** 需求:* 某電影院目前正在上映國產(chǎn)大片,共 100 張票,而它有 3 個窗口賣票,請設計一個程序模擬該電影院賣票。** 利用同步方法完成**/MyThread t1 = new MyThread();MyThread t2 = new MyThread();MyThread t3 = new MyThread();t1.setName("窗口1");t2.setName("窗口2");t3.setName("窗口3");t1.start();t2.start();t3.start();} }
6.2 死鎖
- 死鎖示例代碼
public class MyThread extends Thread{static Object objA = new Object();static Object objB = new Object();@Overridepublic void run() {// 1. 循環(huán)while (true) {if ("線程A".equals(getName())) {synchronized (objA) {System.out.println("線程 A 拿到了 A 鎖,準備拿 B 鎖");synchronized (objB) {System.out.println("線程 A 拿到了 B 鎖,順利執(zhí)行完一輪");}}} else if ("線程B".equals(getName())) {if ("線程B".equals(getName())) {synchronized (objB) {System.out.println("線程 B 拿到了 B 鎖,準備拿 A 鎖");synchronized (objA) {System.out.println("線程 B 拿到了 A 鎖,順利執(zhí)行完一輪");}}}}}}
}
public class ThreadDemo {public static void main(String[] args) {/*** 死鎖*/MyThread t1 = new MyThread();MyThread t2 = new MyThread();t1.setName("線程A");t2.setName("線程B");t1.start();t2.start();}
}
執(zhí)行這個代碼就會出現(xiàn)死鎖的情況。
7. 生產(chǎn)者和消費者
7.1 等待喚醒機制
等待喚醒機制思路(Desk、Cook、Foodie)
示例代碼(寫法一):
public class Desk {/*** 作用:控制生產(chǎn)者和消費者的執(zhí)行*/// 是否有面條 0:沒有面條 1:有面條public static int foodFlog = 0;// 總個數(shù)public static int count = 10;// 鎖對象public static Object lock = new Object();
}
public class Cook extends Thread{@Overridepublic void run() {/*** 1. 循環(huán)* 2. 同步代碼塊* 3. 判斷共享數(shù)據(jù)是否到了尾聲(到了尾聲)* 4. 判斷共享數(shù)據(jù)是否到了尾聲(沒有到尾聲,執(zhí)行核心邏輯)*/while (true) {synchronized (Desk.lock) {if (Desk.count == 0) {break;} else {// 判斷桌子上是否有食物// 如果有,就等待if (Desk.foodFlog == 1) {try {Desk.lock.wait();} catch (InterruptedException e) {e.printStackTrace();}} else {// 如果沒有,就制作食物System.out.println("廚師做了一碗面條");// 修改桌子上的食物狀態(tài)Desk.foodFlog = 1;// 叫醒等待的消費者開吃Desk.lock.notifyAll();}}}}}
}
public class Foodie extends Thread{@Overridepublic void run() {/*** 1. 循環(huán)* 2. 同步代碼塊* 3. 判斷共享數(shù)據(jù)是否到了末尾(到了末尾)* 4. 判斷共享數(shù)據(jù)是否到了末尾(沒到末尾,執(zhí)行核心邏輯)*/while (true) {synchronized (Desk.lock) {if (Desk.count == 0) {break;} else {// 先判斷桌子上是否有面條if (Desk.foodFlog == 0) {// 如果沒有,就等待try {Desk.lock.wait(); // 讓當前線程跟鎖進行綁定} catch (InterruptedException e) {e.printStackTrace();}} else {// 把吃的總數(shù) -1Desk.count--;// 如果有,就開吃System.out.println("吃貨正在吃面條,還能再吃" + Desk.count + "碗!!!");// 吃完之后,喚醒廚師繼續(xù)做Desk.lock.notifyAll();// 修改桌子的狀態(tài)Desk.foodFlog = 0;}}}}}
}
示例代碼(寫法二 — 阻塞隊列方式實現(xiàn)):
? 阻塞隊列的繼承結構
public class Cook extends Thread{ArrayBlockingQueue<String> queue;public Cook(ArrayBlockingQueue<String> queue) {this.queue = queue;}@Overridepublic void run() {while (true) {// 不斷的把面條放到阻塞隊列中try {queue.put("面條");System.out.println("廚師放了一碗面條");} catch (InterruptedException e) {e.printStackTrace();}}}
}
public class Foodie extends Thread{ArrayBlockingQueue<String> queue;public Foodie(ArrayBlockingQueue<String> queue) {this.queue = queue;}@Overridepublic void run() {while (true) {// 不斷從阻塞隊列中獲取面條try {String food = queue.take();System.out.println(food);} catch (InterruptedException e) {e.printStackTrace();}}}
}
public class ThreadDemo {public static void main(String[] args) {/*** 需求:利用阻塞隊列完成生產(chǎn)者和消費者(等待喚醒機制)的代碼** 細節(jié):* 生產(chǎn)者和消費者必須使用同一個阻塞隊列*/// 1. 創(chuàng)建阻塞隊列的對象ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(1);// 2. 創(chuàng)建線程的對象,并把阻塞隊列傳遞過去Cook c = new Cook(queue);Foodie f = new Foodie(queue);// 3. 開啟線程c.start();f.start();}
}
7.2 線程的狀態(tài)
但是再 JVM 里面是沒有定義運行狀態(tài)的
8. 練習
8.1 多線程實現(xiàn)搶紅包
public class MyThread extends Thread{// 共享數(shù)據(jù)// 100 塊,分成了3個紅包static double money = 100;static int count = 3;// 最小的中獎金額static final double MIN = 0;@Overridepublic void run() {// 同步代碼塊synchronized (MyThread.class) {if (count == 0) {// 判斷,共享數(shù)據(jù)是否到了末尾(已經(jīng)到末尾)System.out.println(getName() + "沒有搶到紅包!");} else {// 判斷,共享數(shù)據(jù)是否到了末尾(沒有到末尾)// 定義一個變量,表示中獎金額double prize = 0;if (count == 1) {// 表示此時是最后一個紅包// 就無需隨機,剩余所有的錢都是中獎金額prize = money;} else {// 表示第一次,第二次(隨機)Random r = new Random();double bounds = money - (count - 1) * MIN;prize = r.nextDouble(bounds);if (prize < MIN) {prize = MIN;}}// 從 money 中去掉當前中獎的金額money = money - prize;// 紅包的個數(shù) -1count--;// 本次紅包的信息進行打印System.out.println(getName() + "搶到了" + prize + "元");}}}
}
public class Test {public static void main(String[] args) {/*** 微信中的搶紅包也用了多線程。* 假設:100塊,分成了3個包,現(xiàn)在有5個人去搶。* 其中,紅包是共享數(shù)據(jù)。* 5個人是5條線程* 打印結果如下:* xxx 搶到了 xxx 元* xxx 搶到了 xxx 元* xxx 沒搶到* xxx 沒搶到**/// 創(chuàng)建線程對象MyThread t1 = new MyThread();MyThread t2 = new MyThread();MyThread t3 = new MyThread();MyThread t4 = new MyThread();MyThread t5 = new MyThread();// 給線程設置名字t1.setName("小A");t2.setName("小B");t3.setName("小C");t4.setName("小D");t5.setName("小E");// 啟動線程t1.start();t2.start();t3.start();t4.start();t5.start();}
}
8.2 多線程實現(xiàn)抽獎
public class MyThread extends Thread{ArrayList<Integer> list;public MyThread(ArrayList<Integer> list) {this.list = list;}@Overridepublic void run() { // 1 // 2// 循環(huán)// 同步代碼塊// 判斷// 判斷while (true) {synchronized (MyThread.class) {if (list.size() == 0) {break;} else {// 繼續(xù)抽獎Collections.shuffle(list);int price = list.remove(0);System.out.println(getName() + "又產(chǎn)生了一個 " + price + " 元大獎");}}try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}
}
public class Test {public static void main(String[] args) {/*** 有一個抽獎池,該抽獎池中存放了獎勵的金額,該抽獎池中的獎項為{18,5,20,50,100,200,500,800,2,80,300,700);* 創(chuàng)建兩個抽獎箱(線程)設置線程名稱分別為“抽獎箱1”,“抽獎箱2”* 隨機從抽獎池中獲取獎項元素并打印在控制臺上,格式如下:* 每次抽出一個獎項就打印一個(隨機)* 抽獎箱1 又產(chǎn)生了一個 10 元大獎* 抽獎箱1 又產(chǎn)生了一個 100 元大獎* 抽獎箱1 又產(chǎn)生了一個 200 元大獎* 抽獎箱1 又產(chǎn)生了一個 800 元大獎* 元大獎抽獎箱2 又產(chǎn)生了一個 700* ......*/// 創(chuàng)建獎池ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 18,5,20,50,100,200,500,800,2,80,300,700);// 創(chuàng)建線程MyThread t1 = new MyThread(list);MyThread t2 = new MyThread(list);// 設置名字t1.setName("抽獎箱1");t2.setName("抽獎箱2");// 啟動線程t1.start();t2.start();}
}
8.3 多線程統(tǒng)計并求最大值(解法1)
public class MyThread extends Thread{ArrayList<Integer> list;public MyThread(ArrayList<Integer> list) {this.list = list;}// 線程1static ArrayList<Integer> list1 = new ArrayList<>();// 線程2static ArrayList<Integer> list2 = new ArrayList<>();@Overridepublic void run() { // 1 // 2// 循環(huán)// 同步代碼塊// 判斷// 判斷while (true) {synchronized (MyThread.class) {if (list.size() == 0) {if ("抽獎箱1".equals(getName())) {System.out.println("抽獎箱1" + list1);} else {System.out.println("抽獎箱2" + list2);}break;} else {// 繼續(xù)抽獎Collections.shuffle(list);int price = list.remove(0);if ("抽獎箱1".equals(getName())) {list1.add(price);} else {list2.add(price);}}}try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}
}
public class Test {public static void main(String[] args) {/*** 有一個抽獎池,該抽獎池中存放了獎勵的金額,該抽獎池中的獎項為{10,5,20,50,100,200,500,800,2,80,300,700};* 創(chuàng)建兩個抽獎箱(線程)設置線程名稱分別為“抽獎箱1”,“抽獎箱2”* 隨機從抽獎池中獲取獎項元素并打印在控制臺上,格式如下:* 每次抽的過程中,不打印,抽完時一次性打印(隨機) 在此次抽獎過程中,抽獎箱1總共產(chǎn)生了6個獎項。* 分別為: 10,20,100,500,2,300最高獎項為300元,總計額為932元* 在此次抽獎過程中,抽獎箱2總共產(chǎn)生了6個獎項。* 分別為: 5,50,200,800,80,700最高獎項為800元,總計額為1835元*/// 創(chuàng)建獎池ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 18,5,20,50,100,200,500,800,2,80,300,700);// 創(chuàng)建線程MyThread t1 = new MyThread(list);MyThread t2 = new MyThread(list);// 設置名字t1.setName("抽獎箱1");t2.setName("抽獎箱2");// 啟動線程t1.start();t2.start();}
}
8.4 多線程統(tǒng)計并求最大值(解法2)
public class MyThread extends Thread{ArrayList<Integer> list;public MyThread(ArrayList<Integer> list) {this.list = list;}@Overridepublic void run() {ArrayList<Integer> boxList = new ArrayList<>();while (true) {synchronized (MyThread.class) {if (list.size() == 0) {System.out.println(getName() + boxList);break;} else {// 繼續(xù)抽獎Collections.shuffle(list);int price = list.remove(0);boxList.add(price);}}try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}
}
public class Test {public static void main(String[] args) {/*** 有一個抽獎池,該抽獎池中存放了獎勵的金額,該抽獎池中的獎項為{10,5,20,50,100,200,500,800,2,80,300,700};* 創(chuàng)建兩個抽獎箱(線程)設置線程名稱分別為“抽獎箱1”,“抽獎箱2”* 隨機從抽獎池中獲取獎項元素并打印在控制臺上,格式如下:* 每次抽的過程中,不打印,抽完時一次性打印(隨機) 在此次抽獎過程中,抽獎箱1總共產(chǎn)生了6個獎項。* 分別為: 10,20,100,500,2,300最高獎項為300元,總計額為932元* 在此次抽獎過程中,抽獎箱2總共產(chǎn)生了6個獎項。* 分別為: 5,50,200,800,80,700最高獎項為800元,總計額為1835元*/// 創(chuàng)建獎池ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 18,5,20,50,100,200,500,800,2,80,300,700);// 創(chuàng)建線程MyThread t1 = new MyThread(list);MyThread t2 = new MyThread(list);// 設置名字t1.setName("抽獎箱1");t2.setName("抽獎箱2");// 啟動線程t1.start();t2.start();}
}
8.4 多線程之間的比較
public class MyCallable implements Callable<Integer> {ArrayList<Integer> list;public MyCallable(ArrayList<Integer> list) {this.list = list;}@Overridepublic Integer call() throws Exception {ArrayList<Integer> boxList = new ArrayList<>();while (true) {synchronized (MyCallable.class) {if (list.size() == 0) {System.out.println(Thread.currentThread().getName() + boxList);break;} else {// 繼續(xù)抽獎Collections.shuffle(list);int price = list.remove(0);boxList.add(price);}}Thread.sleep(10);}// 把集合中的最大值返回if (boxList.size() == 0) {return null;} else {return Collections.max(boxList);}}
}
public class Test {public static void main(String[] args) throws ExecutionException, InterruptedException {/*** 有一個抽獎池,該抽獎池中存放了獎勵的金額,該抽獎池中的獎項為{10,5,20,50,100,200,500,800,2,80,300,700};* 創(chuàng)建兩個抽獎箱(線程)設置線程名稱分別為 "抽獎箱1","抽獎箱2"* 隨機從抽獎池中獲取獎項元素并打印在控制臺上,格式如下:* 在此次抽獎過程中,抽獎箱1總共產(chǎn)生了6個獎項,分別為: 10,20,100,500,2,300* 最高獎項為300元,總計額為932元** 在此次抽獎過程中,抽獎箱2總共產(chǎn)生了6個獎項,分別為: 5,50,200,800,80,700* 最高獎項為800元,總計額為1835元** 在此次抽獎過程中,抽獎箱2中產(chǎn)生了最大獎項,該獎項金額為800元* 核心邏輯:獲取線程抽獎的最大值(看成是線程運行的結果)* 以上打印效果只是數(shù)據(jù)模擬,實際代碼運行的效果會有差異*/// 創(chuàng)建獎池ArrayList<Integer> list = new ArrayList<>();Collections.addAll(list, 10,5,20,50,100,200,500,800,2,80,300,700);// 創(chuàng)建多線程要運行的參數(shù)對象MyCallable mc = new MyCallable(list);// 創(chuàng)建多線程運行結果的管理對象FutureTask<Integer> ft1 = new FutureTask<>(mc);FutureTask<Integer> ft2 = new FutureTask<>(mc);// 創(chuàng)建線程對象Thread t1 = new Thread(ft1);Thread t2 = new Thread(ft2);// 設置名字t1.setName("抽獎箱1");t2.setName("抽獎箱2");// 開啟線程t1.start();t2.start();Integer max1 = ft1.get();Integer max2 = ft2.get();System.out.println(max1);System.out.println(max2);// 在此次抽獎過程中,抽獎箱2中產(chǎn)生了最大獎項,該獎項金額為800元System.out.println("在此次抽獎過程中,抽獎箱"+(ft1.get()==800?t1.getName():t2.getName())+"中產(chǎn)生了最大獎項,該獎項金額為800元");}
}
9. 線程池
9.1 以前寫多線程的弊端
- 弊端1:用到線程就得創(chuàng)建
- 弊端2:用完之后線程就消失
9.3 線程池主要核心原理
- 創(chuàng)建一個池子,池子中是空的
- 提交任務時,池子會創(chuàng)建新的線程對象,任務執(zhí)行完畢,線程歸還給池子,下回再次提交任務時,不需要創(chuàng)建新的線程,直接復用已有的線程即可。
- 但是如果提交任務的時候,池子中沒有空閑的線程,也無法創(chuàng)建新的線程,任務就會排隊等待。
9.3 線程池代碼實現(xiàn)
- 創(chuàng)建線程池
- 提交任務
- 所有任務全部執(zhí)行完畢,關閉線程池
newCachedThreadPool 演示
public class MyThreadPoolDemo {public static void main(String[] args) throws InterruptedException {/*** public static ExecutorService newCachedThreadPool() 創(chuàng)建一個沒有上限的線程池* public static ExecutorService newFixedThreadPool(int nThreads) 創(chuàng)建有上線的線程池*/// newCachedThreadPool 演示// 1. 獲取線程池的對象ExecutorService pool1 = Executors.newCachedThreadPool();Thread.sleep(1000);// 2. 提交任務pool1.submit(new MyRunnable());Thread.sleep(1000);pool1.submit(new MyRunnable());Thread.sleep(1000);pool1.submit(new MyRunnable());Thread.sleep(1000);pool1.submit(new MyRunnable());Thread.sleep(1000);pool1.submit(new MyRunnable());// 3. 銷毀線程池
// pool1.shutdown();}
}
public class MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "---");}
}
運行效果:可以看到會一直在服用線程池中的線程1。
newFixedThreadPool 演示
public class MyThreadPoolDemo {public static void main(String[] args) throws InterruptedException {/*** public static ExecutorService newCachedThreadPool() 創(chuàng)建一個沒有上限的線程池* public static ExecutorService newFixedThreadPool(int nThreads) 創(chuàng)建有上線的線程池*/// newFixedThreadPool 演示// 1. 獲取線程池的對象ExecutorService pool1 = Executors.newFixedThreadPool(3);// 2. 提交任務pool1.submit(new MyRunnable());pool1.submit(new MyRunnable());pool1.submit(new MyRunnable());pool1.submit(new MyRunnable());pool1.submit(new MyRunnable());// 3. 銷毀線程池
// pool1.shutdown();}
}
public class MyRunnable implements Runnable{@Overridepublic void run() {for (int i = 1; i <= 100; i++) {System.out.println(Thread.currentThread().getName() + "---" + i);}}
}
在運行的結果可以看到雖然 new 的線程大于3個,但是實際生成的線程只有3個。
或者我們可以使用 DEBUG 的方式查看結果
在長度為3的線程池中,創(chuàng)建了4個線程之后,線程池的長度為3,在外面的等待的任務數(shù)為1。
9.4 自定義線程池詳解
注意:Java 默認的任務拒絕策略是 AbortPolicy,默認策略:丟棄任務并拋出 PejectdExecutionException 異常
拒接策略
創(chuàng)建自定義線程的構造方法參數(shù)解析:
自定義線程池小結:
- 當核心線程滿時,再提交任務就會排隊
- 當核心線程滿,隊伍滿時,會創(chuàng)建臨時線程
- 當核心線程滿時,隊伍滿,臨時線程滿時,會觸發(fā)任務策略
學習視頻:https://www.bilibili.com/video/BV1LG4y1T7n2?p=1&vd_source=6108736e361d963b64f872fefb8bc1e7