Java多執行緒(筆記版,內附程式碼和視訊連結)
##和大家分享一下學習筆記
##視訊連結指向的是狂神說的教學視訊(免費觀看的)
##如果有錯誤的地方還請各位大佬批評指正
##如果涉及侵權還請聯絡我刪除
多執行緒
執行緒開啟後不一定立即執行,由CPU排程
1. 多執行緒建立方式
1.1建立執行緒方式1:繼承Thread類,重寫run方法執行緒體,呼叫start();
/* 執行緒開啟後不一定立即執行,由cpu安排排程 */ //建立執行緒方式1:繼承Thread類,重寫run方法執行緒體,呼叫start(); //繼承Thread類 public class TestThread1 extends Thread{ //重寫run方法執行緒體 public void run() { for (int i = 0; i < 20; i++) { System.out.println("Jay " + i); } } public static void main(String[] args) { //建立一個執行緒物件 TestThread1 testThread1 = new TestThread1(); //呼叫start()方法開啟執行緒 testThread1.start(); for (int i = 0; i < 20; i++) { System.out.println("Soul " + i); } } }
package Jay; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; /* 練習Thread,實現多執行緒同步下載圖片 */ public class TestThread2 extends Thread{ private String url; private String name; public TestThread2(String url, String name){ this.url = url; this.name = name; } //下載圖片的執行緒執行體 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://cdn.jsdelivr.net/gh/filess/img17@main/2021/05/07/1620371242789-b286c6f7-a06c-48c7-a53b-3a86d18cea97.png", "p1.png"); TestThread2 t2 = new TestThread2("https://cdn.jsdelivr.net/gh/filess/img16@main/2021/05/07/1620377761880-1d4715d4-482c-4d52-a5aa-210a1a354c77.png", "p2.png"); TestThread2 t3 = new TestThread2("https://cdn.jsdelivr.net/gh/filess/img8@main/2021/05/07/1620377156603-8b53ee53-8de0-4f81-b667-3df6ce555064.png", "p3.png"); t1.start(); t2.start(); t3.start(); } } //下載器 class WebDownloader{ public void downloader(String url, String name){ try { FileUtils.copyURLToFile(new URL(url), new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("IO異常,downloader下載出現問題"); } } }
1.2 建立執行緒方法2:實現runnable介面,重寫run方法執行執行緒需要丟入runnable介面實現類,呼叫start方法
//建立執行緒方法2:實現runnable介面,重寫run方法執行執行緒需要丟入runnable介面實現類,呼叫start方法 public class TestThread3 implements Runnable{ //重寫run方法執行緒體 public void run() { for (int i = 0; i < 20; i++) { System.out.println("Jay " + i); } } public static void main(String[] args) { //建立runnable介面的實現類物件 TestThread3 testThread3 = new TestThread3(); //建立執行緒物件,通過執行緒物件來開啟我的執行緒(代理) new Thread(testThread3).start(); for (int i = 0; i < 20; i++) { System.out.println("Soul " + i); } } }
多個執行緒同時操作同一物件,執行緒不安全,資料紊亂
//多個執行緒同時操作同一物件,執行緒不安全,資料紊亂
//買火車票的例子
public class TestThread4 implements Runnable{
private int ticketNums = 10;
public void run(){
while (true){
if (ticketNums <= 0){
break;
}
/*try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums-- + "票");
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket, "小明").start();
new Thread(ticket, "小紅").start();
new Thread(ticket, "小黃").start();
}
}
龜兔賽跑
import kotlin.reflect.jvm.internal.impl.descriptors.Visibilities;
//模擬龜兔賽跑
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子") && i % 60 == 0)
{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (gameOver(i)) break;
System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "步");
}
}
//判斷是否完成比賽
private boolean gameOver (int step){
if (winner != null){
return true;
}
if (step >= 100) {
winner = Thread.currentThread().getName();
System.out.println("Winner is " + winner);
return true;
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race, "兔子").start();
new Thread(race, "烏龜").start();
}
}
1.3 執行緒建立方式3:實現callable介面
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//執行緒建立方式三:實現callable介面
/*
callable的好處
1、可以定義返回值
2、可以丟擲異常
*/
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
public TestCallable(String url, String name){
this.url = url;
this.name = name;
}
//下載圖片的執行緒執行體
public Boolean call(){
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println(name + " 檔案下載成功");
return true;
}
public static void main(String[] args) {
TestCallable t1 = new TestCallable("https://cdn.jsdelivr.net/gh/filess/img17@main/2021/05/07/1620371242789-b286c6f7-a06c-48c7-a53b-3a86d18cea97.png", "p1.png");
TestCallable t2 = new TestCallable("https://cdn.jsdelivr.net/gh/filess/img16@main/2021/05/07/1620377761880-1d4715d4-482c-4d52-a5aa-210a1a354c77.png", "p2.png");
TestCallable t3 = new TestCallable("https://cdn.jsdelivr.net/gh/filess/img8@main/2021/05/07/1620377156603-8b53ee53-8de0-4f81-b667-3df6ce555064.png", "p3.png");
//建立執行服務:
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交執行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
//關閉服務
ser.shutdownNow();
}
}
//下載器
class WebDownloader{
public void downloader(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO異常,downloader下載出現問題");
}
}
}
2. 靜態代理模式
package Jay;
/*
靜態代理:
1、真實物件和代理物件都要實現一個介面
2、代理物件需要代理真是角色
*/
public class StaticProxy{
public static void main(String[] args) {
new MarryCompany(new you()).happyMarry();
}
}
interface Marry{
public void happyMarry();
}
//真實角色結婚
class you implements Marry{
@Override
public void happyMarry() {
System.out.println("源寶結婚了");
}
}
//婚慶公司代理
class MarryCompany implements Marry{
private Marry target;
public MarryCompany(Marry target) {
this.target = target;
}
@Override
public void happyMarry() {
berfore();
this.target.happyMarry();//這是真實物件
after();
}
private void after() {
System.out.println("收尾款");
}
private void berfore() {
System.out.println("佈置場地");
}
}
3. Lamda表示式
3.1 為什麼使用lamda表示
- 避免匿名內部類定義過多
- 使程式碼看起來簡潔,去掉無意義的程式碼,只留下核心邏輯
- 其實質屬於函數語言程式設計的概念
3.2 函式式介面的定義
- 任何介面,如果只包含唯一一個抽象方法,那麼它就是一個函式式介面
- 對於函式式介面,我們可以通過lamda表示式來建立介面的物件
package thread.lamda;
/*
推導lamda表示式
*/
public class TestLamda01 {
//3.靜態內部類
static class Like2 implements ILike{
@Override
public void lamda() {
System.out.println("I like lamda2!");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lamda();
like = new Like2();
like.lamda();
//4.區域性內部類
class Like3 implements ILike{
@Override
public void lamda() {
System.out.println("I like lamda3!");
}
}
like = new Like3();
like.lamda();
//5.匿名內部類,沒有類的名稱,必須藉助介面或者父類
like = new ILike() {
@Override
public void lamda() {
System.out.println("I like lamda4!");
}
};
like.lamda();
//6.用lamda簡化
like = ()->{
System.out.println("I like lamda5!");
};
like.lamda();
}
}
//1.定義一個函式式介面
interface ILike{
void lamda();
}
//2.實現類
class Like implements ILike{
@Override
public void lamda() {
System.out.println("I like lamda!");
}
}
package thread.lamda;
public class TestLamda02 {
//靜態內部類
static class love2 implements ILove{
@Override
public void love(int a) {
System.out.println("I love" + a);
}
}
public static void main(String[] args) {
//普通類實現
ILove love = new love();
love.love(1);
//靜態內部類實現
love = new love2();
love.love(2);
//區域性內部類
class love3 implements ILove{
@Override
public void love(int a) {
System.out.println("I love" + a);
}
}
new love3().love(77);
//匿名內部類
love = new ILove() {
@Override
public void love(int a) {
System.out.println("I love" + a);
}
};
love.love(3);
//lamda 簡化
love = (int a)->{
System.out.println("I love" + a);
};
love.love(4);
}
}
interface ILove{
void love(int a);
}
class love implements ILove{
@Override
public void love(int a) {
System.out.println("I love" + a);
}
}
3.3 lamda簡化形式
//簡化形式1
love = (a) -> {
System.out.println("I love" + a);
};
//簡化形式2(引數<=1)
love = a -> {
System.out.println("I love" + a);
};
//簡化形式3(程式碼只有一行)
love = a -> System.out.println("I love" + a);
4. 執行緒狀態和方法
執行緒一旦進入死亡狀態,就不能再次啟動
4.1 五大狀態
* 建立狀態(new)
* 就緒狀態(start)
* 執行狀態
* 阻塞狀態(sleep,wait)
* 死亡狀態
4.2 執行緒方法
4.3 停止執行緒
- 推薦執行緒自己停下來(不建議死迴圈)
- 建議使用一個標誌位進行終止變數(當flag= false,則終止執行緒執行)
- 不要使用stop或者destroy等過時或者JDK不建議使用的方法
package thread.methods;
//測試stop
public class TestStop implements Runnable{
//1.設定一個標誌位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run ....... Thread" + i++);
}
}
//2.設定一個公開的方法停止執行緒,轉換標誌位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main" + i);
if (i == 900){
testStop.stop();
System.out.println("執行緒已經停止");
}
}
}
}
4.4 執行緒休眠(sleep)
* sleep(時間)指定當前執行緒阻塞的毫秒數
* sleep存在異常InterruptedException
* sleep時間達到後,執行緒進入就緒狀態
* sleep可以模擬網路延時,倒計時等
* 每一個物件都有一個鎖,sleep不會釋放鎖
4.5 執行緒禮讓(yield)
package thread.methods;
//測試禮讓執行緒
public class TestYield {
public static void main(String[] args) {
//lamda表示式
Runnable myYield = ()->{
System.out.println(Thread.currentThread().getName() + "執行緒開始執行");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "執行緒執行結束");
};
new Thread(myYield, "a").start();
new Thread(myYield, "b").start();
}
}
//class MyYield implements Runnable{
//
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + "執行緒開始執行");
// Thread.yield();
// System.out.println(Thread.currentThread().getName() + "執行緒執行結束");
// }
//}
4.6 合併執行緒(Join)
* Join合併執行緒,待此執行緒執行完成後,再執行其他執行緒,其他執行緒阻塞
* 可以想象成插隊
package thread.methods;
//測試join方法
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("VIP來了" + i);
}
}
public static void main(String[] args) throws InterruptedException {
//啟動我們的執行緒
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主執行緒
for (int i = 0; i < 500; i++) {
if (i == 100){
thread.join();
}
System.out.println("main" + i);
}
}
}
4.7 觀測執行緒狀態
package thread.state;
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/////");
});
//觀察狀態(new)
Thread.State state = thread.getState();
System.out.println(state);
//run
thread.start();
state = thread.getState();
System.out.println(state);
//只要執行緒不終止,就一直輸出狀態
while (state != Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();//更新執行緒狀態
System.out.println(state);
}
}
}
5. 執行緒優先順序
優先順序低只是意味著獲得排程的概率低,並不是優先順序低就不會被呼叫了,這都是看CPU排程
* 執行緒的優先順序用數字表示,範圍從1~10
* Thread.MIN_PRIORITY = 1
* Thread.MAX_PRIORITY =10
* Thread.NORM_PRIORITY = 5
* 使用以下方式改變或者獲取優先順序
* getPriority()
* setPriority(int xxx)
package thread.state;
//測試執行緒的優先順序
public class TestPriority {
public static void main(String[] args) {
//主執行緒優先順序
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
//建立執行緒
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
t1.setPriority(10);
t1.start();
t2.start();
t3.setPriority(8);
t3.start();
t6.setPriority(1);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" +Thread.currentThread().getPriority());
}
}
6. 守護(daemon)執行緒
* 執行緒分為使用者執行緒和守護執行緒
* 虛擬機器必須確保使用者執行緒執行完畢(main)
* 虛擬機器不用等待守護執行緒執行完畢,如後臺記錄操作日誌,監控記憶體,垃圾回收等待(gc)
package thread.methods;
//測試守護執行緒
public class TestDaemon {
public static void main(String[] args) {
Love love = new Love();
You you = new You();
Thread thread = new Thread(love);
thread.setDaemon(true);//預設是false表示是使用者執行緒
thread.start();//守護執行緒啟動
new Thread(you).start();//使用者執行緒啟動
}
}
//守護執行緒
class Love implements Runnable{
@Override
public void run() {
while (true){
System.out.println("愛與你相伴");
}
}
}
//使用者執行緒
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("獨行,相伴");
}
System.out.println("-====goodbye!world!====-");
}
}
7. 執行緒同步
併發:同一個物件被多個執行緒同時操作 形成條件:佇列和鎖(鎖機制synchronized)
* 上萬人同時搶100張票
* 兩個銀行同時取錢
7.1 三大不安全案例
package thread.syn;
//不安全的買票
//執行緒不安全,有負數
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket, "小明").start();
new Thread(buyTicket, "小紅").start();
new Thread(buyTicket, "小杰").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums = 10;
boolean flag = true;
public void run() {
while (flag){
if (ticketNums <= 1) flag = false;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 拿到" + ticketNums--);
}
}
}
package thread.syn;
//銀行取錢
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100000, "結婚基金");
Drawing you = new Drawing(account, 5000, "yourself");
Drawing yourWife = new Drawing(account, 10000, "yourWife");
you.start();
yourWife.start();
}
}
class Account{
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawing extends Thread{
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account, int drawingMoney, String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
if (account.money - drawingMoney < 0){
System.out.println(this.getName()+ "餘額不足");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "餘額為" + account.money);
//Thread.currentThread().getName() == this.getName();
System.out.println(this.getName() + "手裡的錢為" + nowMoney);
}
}
package thread.syn;
//表格
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
new Thread(()->{list.add(Thread.currentThread().getName());}).start();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
7.2 同步方法
public synchronized void method(int args){} 同步方法的同步監聽器就是this,即物件本身,或者是class
package thread.syn;
//安全的買票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket, "小明").start();
new Thread(buyTicket, "小紅").start();
new Thread(buyTicket, "小杰").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums = 10;
boolean flag = true;
public void run() {
while (flag){
buy();
}
}
//synchronized 同步方法,鎖的是this
private synchronized void buy() {
if (ticketNums <= 0) {flag = false;return;}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 拿到" + ticketNums--);
}
}
7.3 同步塊
synchronized(Obj){} Obj可以是任何物件,但是推薦使用共享資源(增刪改)作為同步監視器
* 同步監視器的執行過程
* 第一個執行緒訪問,鎖定同步監視器,執行其中程式碼。
* 第二個執行緒訪問,發現同步監視器被鎖定,無法訪問
* 第一個執行緒訪問完畢,解鎖同步監視器
* 第二執行緒訪問,發現同步監視器沒有鎖,然後鎖定並訪問
package thread.syn;
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100000, "結婚基金");
Drawing you = new Drawing(account, 5000, "yourself");
Drawing yourWife = new Drawing(account, 10000, "yourWife");
you.start();
yourWife.start();
}
}
class Account{
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawing extends Thread{
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account, int drawingMoney, String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
synchronized (account){
if (account.money - drawingMoney < 0){
System.out.println(this.getName()+ "餘額不足");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name + "餘額為" + account.money);
//Thread.currentThread().getName() == this.getName();
System.out.println(this.getName() + "手裡的錢為" + nowMoney);
}
}
}
package thread.syn;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 100000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());}
}).start();
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); 自帶鎖的list
package thread.syn;
import java.util.concurrent.CopyOnWriteArrayList;
//測試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(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
7.4 死鎖
死鎖:某一個同步塊同時擁有“兩個以上物件的鎖”
package thread.syn;
//死鎖:多個執行緒互相抱著對方需要的資源,然後形成僵持
public class DeadLock {
public static void main(String[] args) {
MakeUp g1 = new MakeUp(0,"灰姑娘");
MakeUp g2 = new MakeUp(1,"白雪公主");
g1.start();
g2.start();
}
}
//口紅
class LipStick{}
//鏡子
class Mirror{}
class MakeUp extends Thread {
//需要的資源只有一份,用static來保證
static LipStick lipStick = new LipStick();
static Mirror mirror = new Mirror();
int choice;//選擇
String name;//使用化妝品的人
MakeUp(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妝,互相持有對方的資源
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipStick) {//獲得口紅的鎖
System.out.println(this.name + "獲得口紅");
Thread.sleep(1000);
}
synchronized (mirror) {//獲得鏡子的鎖
System.out.println(this.name + "獲得鏡子的鎖");
}
} else {
synchronized (mirror) {//獲得鏡子的鎖
System.out.println(this.name + "獲得鏡子的鎖");
Thread.sleep(2000);
}
synchronized (lipStick) {//獲得口紅的鎖
System.out.println(this.name + "獲得口紅的鎖");
}
}
}
}
7.5 鎖(顯性LOCK)
package thread.syn;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2, "小明").start();
new Thread(testLock2, "小杰").start();
new Thread(testLock2, "小王").start();
}
}
class TestLock2 implements Runnable{
private int tickNums = 10;
boolean flag = true;
private final ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
try{
reentrantLock.lock();
while (flag){
if (tickNums <= 0 ){
flag = false;
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "獲得了" + tickNums--);
}
}finally {
reentrantLock.unlock();
}
}
}
8. 執行緒協作
生產者消費者問題:生產者和消費者共享同一個資源,並且生產者和消費者之間相互依賴,互為條件
作用 | 方法名 |
---|---|
表示執行緒一直等待,直到其他執行緒通知,與sleep不同,會釋放鎖 | wait() |
指定等待的毫秒數 | wait(long timeout) |
喚醒一個等待狀態的執行緒 | notify() |
喚醒同一個物件上所有呼叫wait()方法的執行緒,優先級別高的執行緒優先排程 | notifyAll() |
8.1 解決方式1
併發協作模型“生產者/消費者模式”-->管程法
* 生產者:負責生產資料的模組(可能是方法,物件,執行緒,程序)
* 消費者:負責處理資料的模組(可能是方法,物件,執行緒,程序)
* 緩衝區:消費者不能直接使用生產者的資料,他們之間有個“緩衝區”
生產者將生產好的資料放入緩衝區,消費者從緩衝區拿出資料
視訊連結
package thread.itc;
//測試:生產者消費者模型-->管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
//生產者
class Producer extends Thread{
SynContainer container;
public Producer(SynContainer container){
this.container = container;
}
//生產
@Override
public void run() {
for (int i = 1; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生產了" + i + "只雞");
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消費者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
//消費
@Override
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println("消費了-->" + container.pop().id + "只雞");
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//產品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//緩衝區
class SynContainer{
//需要一個容器大小
Chicken[] chickens = new Chicken[10];
//容器計數器
int count = 0;
//生產者放入產品
public synchronized void push(Chicken chicken){
//如果容器滿了,需要等待消費者消費
if(count == chickens.length){
//通知消費者消費,生產等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果沒有滿,丟入產品
chickens[count] = chicken;
count++;
//可以通知消費者消費產品
this.notifyAll();
}
//消費者消費產品
public synchronized Chicken pop(){
//判斷能否消費
if (count == 0){
//等待生產者生產
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消費
count--;
Chicken chicken = chickens[count];
//吃完了,通知生產者生產
this.notifyAll();
return chicken;
}
}
8.2 解決方式2
併發協作模型“生產者/消費者模式”-->訊號燈法
package thread.itc;
////測試:生產者消費者模型-->訊號燈法
public class TestPC2 {
public static void main(String[] args) {
Program program = new Program();
new Player(program).start();
new Audience(program).start();
}
}
//生產者-->演員
class Player extends Thread{
Program program;
public Player(Program program){
this.program = program;
}
@Override
public void run() {
for (int i = 1; i < 20; i++) {
this.program.show ("Jay's專場", i);
}
}
}
//消費者-->觀眾
class Audience extends Thread{
Program program;
public Audience(Program program){
this.program = program;
}
@Override
public void run() {
for (int i = 1; i < 20; i++) {
this.program.clap();
}
}
}
//產品-->節目
class Program{
//演員表演,觀眾觀看 T
//觀眾鼓掌,演員致敬 F
String name;//表演的節目
int order;//節目序號
boolean flag = true;//訊號燈
//表演
public synchronized void show (String name, int order){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演員表演了" + name + "第" + order + "個節目");
//觀眾鼓掌喝彩,演員致敬
this.notifyAll();
this.name = name;
this.order = order;
this.flag = !this.flag;
}
//鼓掌
public synchronized void clap(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("觀眾看完" + name + "第" + order + "個節目,會場響起熱烈掌聲,演員們鞠躬致敬");
this.notifyAll();
this.flag = !this.flag;
}
}
9. 執行緒池
* 背景:經常建立和銷燬、使用量特別大的資源,比如併發情況下的執行緒,對效能影響很大
* 思路:提前建立好多個執行緒,放到執行緒池中,使用時直接獲取,使用完放回池中。可以避免繁建立銷燬、實現重複利用。類似生活中的公共交通工具(單車)。
* 好處:
* 提高響應速度(減少了建立新執行緒的時間)
* 降低資源消耗(重複利用執行緒池中執行緒,不用每次都建立)
* 便於執行緒管理
newFixedThreadPool:執行緒池大小
corePoolSize:核心池的大小
maximumPoolSize:最大執行緒數
keepAliveTime:執行緒沒有任務時最多保持多長時間後會終止
執行緒池相關API:ExecutorService 和 Executors
void execute(Runnable command):執行任務/命令,沒有返回值,一般用來執行Runnable
<T>Future<T>submit(Callable<T>task):執行任務,有返回值,一般用來執行
Callablevoid shutdown():關閉連線池
Executors:工具類、執行緒池的工廠類,用於建立並返回不同型別的執行緒池
package thread.syn;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//測試執行緒池
public class TestPool {
public static void main(String[] args) {
//1.建立執行緒池
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.關閉連線
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}