日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

JAVA多线程总结(笔记)

發(fā)布時間:2023/12/3 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JAVA多线程总结(笔记) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

線程的特點

  • 線程就是獨立的執(zhí)行路徑;
  • 在線程運行時,即使沒有自己創(chuàng)建線程,后臺也會有多個線程,如主線程,gc線程;
  • main()稱之為主線程,為系統(tǒng)的入口,用于執(zhí)行整個程序;
  • 在一個進(jìn)程中,如果開辟了多個線程,線程的運行由調(diào)度器安排調(diào)度,調(diào)度器是與操作系統(tǒng)緊密相關(guān)的,先后順序是不能人為的干預(yù)的。
  • 對同一份資源操作時,會存在資源搶奪的問題,需要加入并發(fā)控制;
  • 線程會帶來額外的開銷,如cpu調(diào)度時間,并發(fā)控制開銷。
  • 每個線程在自己的工作內(nèi)存交互,內(nèi)存控制不當(dāng)會造成數(shù)據(jù)不一致

進(jìn)程和線程的區(qū)別

進(jìn)程是操作系統(tǒng)資源分配的基本單位,而線程是處理器任務(wù)調(diào)度和執(zhí)行的基本單位。還存在資源開銷、包含關(guān)系、內(nèi)存分配、影響關(guān)系、執(zhí)行過程等區(qū)別。同一進(jìn)程的線程共享本進(jìn)程的地址空間和資源,而進(jìn)程之間的地址空間和資源相互獨立。

線程創(chuàng)建方式

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-i3ZOerjT-1608708490342)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201222233338560.png)]

1.Thread

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-oaYMfvFx-1608708490345)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201222234526548.png)]

  • 自定義線程類繼承Thread類
  • 重寫run()方法,編寫線程執(zhí)行體
  • 創(chuàng)建線程對象,調(diào)用start()方法啟動線程
//創(chuàng)建線程方式一:繼承thread類,重寫run()方法,調(diào)用start開啟線程//總結(jié):注意,線程開啟不一定立即執(zhí)行,由CPU調(diào)度執(zhí)行 public class ThreadDemo01 extends Thread {@Overridepublic void run() {//run方法線程體for (int i = 0; i <100; i++) {System.out.println("多線程被執(zhí)行了");}}public static void main(String[] args) {//main線程,主線程//創(chuàng)建一個線程對象ThreadDemo01 td1 = new ThreadDemo01();td1.start();//調(diào)用start方法開啟線程for (int i = 0; i <1000 ; i++) {System.out.println("每天都在學(xué)習(xí)java");}} }

練習(xí)

[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-eeB1nHR8-1608708490347)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201222235400735.png)]

package com.dong.thread;import org.apache.commons.io.FileUtils;import java.io.File; import java.io.IOException; import java.net.URL;/*** @author dong* @date 2020/5/24 - 8:39*/ // public class ThreadDemo02 extends Thread{private String url;//保存網(wǎng)絡(luò)圖片地址private String name;//保存的文件名public ThreadDemo02(String url, String name) {this.url = url;this.name = name;}@Overridepublic void run() {WebDownLoader webDownLoader = new WebDownLoader();webDownLoader.downLoader(url,name);System.out.println("圖片下載成功,名為:"+name);}public static void main(String[] args) {ThreadDemo02 t1 = new ThreadDemo02("https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=1561546013,1259770086&fm=85&s=1A21EC02EE337FAF0854119903001062","1.jpg");ThreadDemo02 t2 = new ThreadDemo02("https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=3506652242,2368086075&fm=85&s=8C9F875066675AAE078DE4D6030050F1","2.jpg");ThreadDemo02 t3 = new ThreadDemo02("https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=2623032014,2137091052&fm=85&s=F4C2BE56F74162EE0E5EEC7C03004071","3.jpg");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有問題");//文件下載失敗}} }

2.Runnable接口

public class ThreadDemo03 implements Runnable{@Overridepublic void run() {for (int i = 0; i <200 ; i++) {System.out.println("多線程被執(zhí)行了");}}public static void main(String[] args) {new Thread(new ThreadDemo03()).start();//ThreadDemo02 threadDemo02 = new ThreadDemo02();//Thread thread = new Thread(threadDemo02);代理//thread.start();for (int i = 0; i <1000 ; i++) {System.out.println("每天都在學(xué)習(xí)java");}} }

小結(jié)

  • 繼承Thread類
    • 子類繼承Thread類具備多線程能力
    • 啟動線程:子類對象.start()
    • 不建議使用:避免OOP單繼承局限性
  • 實現(xiàn)Runnable接口

實現(xiàn)接口Runnable具有多線程能力

啟動線程:傳入目標(biāo)對象+Thread對象.start ()

推薦使用:避免單繼承局限性,靈活方便,方便同一對象被多個線程使用

實例

public class ThreadDemo04 implements Runnable{private static String winner;//勝利者 static保證只有一個勝利者@Overridepublic void run() {for (int i = 0; i <=100 ; i++) {//模擬兔子休息if(Thread.currentThread().getName().equals("兔子")&& i%20==0){try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}//判斷是否結(jié)束比賽boolean flag=gameOver(i);//如果比賽結(jié)束了,停止程序if(flag){break;}System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");}}//判斷是否完成比賽private boolean gameOver(int steps){//判斷是否有勝利者if(winner!=null){return true;} {if (steps>=100){winner=Thread.currentThread().getName();System.out.println("winner is:"+winner);return true;}}return false;}public static void main(String[] args) {new Thread(new ThreadDemo04(),"兔子").start();new Thread(new ThreadDemo04(),"烏龜").start();} }

3.實現(xiàn)Callable接口(了解)

  • 實現(xiàn)Callable接口,需要返回值類型
  • 重寫call方法,需要拋出異常
  • 創(chuàng)建目標(biāo)對象
  • 創(chuàng)建執(zhí)行服務(wù):ExecutorService=Executor.newFixedThreadPool(1);
  • 提交執(zhí)行:Futureresult1=ser.submit(t1);
  • 獲取結(jié)果:boolean r1=result.get()
  • 關(guān)閉服務(wù):ser.shutdownNow();
  • package com.kuang.demo02; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.*; public class TestCallable implements Callable<Boolean> {private String url;//保存網(wǎng)絡(luò)圖片地址private String name;//保存的文件名public TestCallable(String url, String name) {this.url = url;this.name = name;}@Overridepublic Boolean call() {WebDownLoader webDownLoader = new WebDownLoader();webDownLoader.downLoader(url,name);System.out.println("圖片下載成功,名為:"+name);return true;}public static void main(String[] args) throws ExecutionException, InterruptedException {TestCallable t1 = new TestCallable("https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=1561546013,1259770086&fm=85&s=1A21EC02EE337FAF0854119903001062","1.jpg");TestCallable t2 = new TestCallable("https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=3506652242,2368086075&fm=85&s=8C9F875066675AAE078DE4D6030050F1","2.jpg");TestCallable t3 = new TestCallable("https://dss0.baidu.com/73t1bjeh1BF3odCf/it/u=2623032014,2137091052&fm=85&s=F4C2BE56F74162EE0E5EEC7C03004071","3.jpg");//創(chuàng)建執(zhí)行服務(wù)ExecutorService ser = Executors.newFixedThreadPool(3);//提交執(zhí)行Future<Boolean> r1 = ser.submit(t1);Future<Boolean> r2 = ser.submit(t2);Future<Boolean> r3 = ser.submit(t3);//獲取結(jié)果boolean rs1=r1.get();boolean rs2=r2.get();boolean rs3=r3.get();//關(guān)閉服務(wù)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有問題");//文件下載失敗}} }

    靜態(tài)代理

    真實對象和代理對象都要實現(xiàn)同一個接口

    代理對象要代理真實角色

    好處:

    代理對象可以做很多真實對象做不了的事情

    真實對象專注做自己的事情

    package com.kuang.demo03; public class StacticProxy {public static void main(String[] args) { // WeddingCompany weddingCompany=new WeddingCompany(new You()); // weddingCompany.HappyMarry();new WeddingCompany(new You()).HappyMarry();} } interface Marry{void HappyMarry(); } class You implements Marry{@Overridepublic void HappyMarry(){System.out.println("afdas");} }class WeddingCompany implements Marry{private Marry target;public WeddingCompany(Marry target){this.target=target;}@Overridepublic void HappyMarry(){before();this.target.HappyMarry();after(); }private void after() {System.out.println("asf"); }private void before() {System.out.println("asdfa");} }

    Lamda表達(dá)式

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-GmTxaGNR-1608708490355)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223104552933.png)]

    函數(shù)式接口

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-Ll6HAooJ-1608708490356)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223104815076.png)]

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-OVOumEzH-1608708490359)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223110252247.png)]

    lamda表達(dá)式簡化

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-90qhdq24-1608708490360)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223111844980.png)]

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-YxZohGaf-1608708490361)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223112035798.png)]

    public class TestLambda1 {//2.靜態(tài)內(nèi)部類static class Love implements ILove {public void ILove(int a) {System.out.println("i like lambda" + a);}}public static void main(String[] args) {Love love=new Love();love.ILove(1);Love love1=new Love();love1.ILove(2);class Love implements ILove {//3.局部內(nèi)部類public void ILove(int a) {System.out.println("i like lambda" + a);}}Love love2 = new Love();love2.ILove(3);//4.匿名內(nèi)部類ILove iLove=new ILove() {@Overridepublic void ILove(int a) {System.out.println("i like lambda" + a);}};iLove.ILove(4);//5.lambda表達(dá)式ILove iLove1=(int a)->{System.out.println("i like lambda" + a);};iLove1.ILove(5);} } //定義一個接口,只有一個方法,函數(shù)式接口 interface ILove{void ILove(int a); }//1.普通實現(xiàn) class Love implements ILove {@Overridepublic void ILove(int a) {System.out.println("i like lambda" + a);} } public class TestLambda2 {public static void main(String[] args) {YouLove youLove=(a,b)->{System.out.println("一句話你說:"+a+b);};youLove.youLove(10,20);} }interface YouLove{void youLove(int a,int b); }

    總結(jié):

  • lambda表達(dá)式只能有一行代碼的情況下才能簡化為一行,如果有多行,那么就用代碼塊包裹
  • 前提是 接口為函數(shù)式接口
  • 多個參數(shù)也可以去掉參數(shù)類型, 要去 掉 就都去掉 ,必須加上括號。
  • 線程狀態(tài)

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-DpOnjVPD-1608708490361)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223112930005.png)]

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-OEAilaW0-1608708490362)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223113054638.png)]

    線程停止

    package com.kuang.demo05;public class TestStop implements Runnable {private boolean flag=true;@Overridepublic void run() {int i=0;while (flag){System.out.println("run.....Thread"+(i++));}}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("線程停止了!");}}} }

    線程休眠

    sleep(時間)指定當(dāng)前線程阻塞的毫秒數(shù);

    sleep存在異常InterruptedException

    sleep時間到達(dá)后線程進(jìn)入就緒狀態(tài)

    sleep可以模擬網(wǎng)絡(luò)延時,倒計時等。

    每一個對象都有一個鎖,sleep不會釋放鎖

    package com.kuang.demo05;import java.text.SimpleDateFormat; import java.util.Date;public class TestSleep2 {public static void main(String[] args) {TestSleep2.tenDown();//打印當(dāng)前系統(tǒng)時間Date startTime=new Date(System.currentTimeMillis());//獲取當(dāng)前系統(tǒng)時間while (true){try {Thread.sleep(1000);System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));startTime=new Date(System.currentTimeMillis());//更新時間} catch (InterruptedException e) {e.printStackTrace();}}}//模擬倒計時public static void tenDown(){int num=10;while (true){try {Thread.sleep(1000);if (num<=0){break;}else{System.out.println("倒計時!!!"+num--+"秒");}} catch (InterruptedException e) {e.printStackTrace();}}} }

    線程禮讓yield

    禮讓線程,讓當(dāng)前正在執(zhí)行的線程暫停,但不阻塞

    將線程從運行狀態(tài)轉(zhuǎn)為就緒狀態(tài)

    讓cpu重新調(diào)度,禮讓不一定成功!看CPU心情。

    package com.kuang.demo05; public class TestYield{public static void main(String[] args) {MyYield yield=new MyYield();new Thread(yield,"a").start();new Thread(yield,"b").start();} } class MyYield implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"線程開始執(zhí)行");Thread.yield();//禮讓System.out.println(Thread.currentThread().getName()+"線程停止執(zhí)行");} }

    線程強制執(zhí)行join

    package com.kuang.demo05; public class TestJoin implements Runnable {@Overridepublic void run() {for (int i = 0; i <10 ; i++) {System.out.println("VIP線程來插隊了!!!"+i);}}public static void main(String[] args) throws InterruptedException { // Thread thread= new Thread(new TestJoin());new Thread(new TestJoin()).start();for (int i = 0; i <400 ; i++) {System.out.println("主線程在排隊!!!"+i);if (i==100){new Thread(new TestJoin()).join();}}} }

    線程狀態(tài)

    Thread.State

    線程狀態(tài),線程可以處于一下狀態(tài)之一:

    • new 尚未啟動的線程處于此狀態(tài)
    • Runnable 在java虛擬機中執(zhí)行的線程處于此狀態(tài)
    • Blocked 被阻塞等待監(jiān)視器鎖定的線程處于此狀態(tài)。
    • Waiting 正在等待另一個線程執(zhí)行特定動作的線程處于此狀態(tài)。
    • Timed Waiting 正在等待另一個線程執(zhí)行動作達(dá)到指定等待時間的線程處于此狀態(tài)。
    • Terminated 已退出的線程處于此狀態(tài)。

    一個線程可以給定時間點處于一個狀態(tài)。這些狀態(tài)是不反映任何操作系統(tǒng)線程狀態(tài)的虛擬機狀態(tài)

    package com.kuang.demo05; 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("");});Thread.State state = thread.getState();System.out.println(state);//newthread.start();//啟動線程state=thread.getState();//runnableSystem.out.println(state);while (state!= Thread.State.TERMINATED){//只要線程不終止就輸入線程狀態(tài)Thread.sleep(100);state=thread.getState();System.out.println(state);}} }

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-2HsC4lq6-1608708490364)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223130000180.png)]

    線程優(yōu)先級

    java提供一個線程調(diào)度器來監(jiān)控程序中啟動后進(jìn)入就緒狀態(tài)的所有線程,線程調(diào)度器按照優(yōu)先級決定應(yīng)該調(diào)度哪個線程來執(zhí)行。

    線程的優(yōu)先級用數(shù)字表示,范圍從1~10。

    使用以下方式改變或獲取優(yōu)先級

    getPriority().setPriority(int xxx)

    package com.kuang.demo05;public class TestPriority {public static void main(String[] args) {MyPriority myPriority = new MyPriority();Thread t1 = new Thread(myPriority);Thread t2 = new Thread(myPriority);Thread t3 = new Thread(myPriority);Thread t4 = new Thread(myPriority);Thread t5 = new Thread(myPriority);Thread t6 = new Thread(myPriority);//先設(shè)置線程優(yōu)先級t1.setPriority(1);t1.start();t2.setPriority(3);t2.start();t3.setPriority(6);t3.start();t4.setPriority(Thread.MAX_PRIORITY);// 優(yōu)先級=10t4.start();t5.setPriority(Thread.MIN_PRIORITY);// 優(yōu)先級=1t6.setPriority(9);t6.start();System.out.println("main");} } class MyPriority implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"---線程被執(zhí)行了!---"+Thread.currentThread().getPriority());} }

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-vRIzDkCg-1608708490365)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223131437565.png)]

    注意:先設(shè)置優(yōu)先級,再start線程!!!

    守護(hù)線程daemon

    • 線程分為用戶線程和守護(hù)線程
    • 虛擬機必須確保用戶線程執(zhí)行完畢
    • 虛擬機不用等待守護(hù)線程執(zhí)行完畢
    • 如,后臺記錄操作日志,監(jiān)控內(nèi)存,垃圾回收等待。。。
    package com.kuang.demo05; public class TestDaemon {public static void main(String[] args) {God god = new God();You you=new You();Thread thread = new Thread(god);thread.setDaemon(true);//默認(rèn)為flase 為用戶線程, true為守護(hù)線程thread.start(); // new Thread(you).start();Thread thread1 = new Thread(you);thread1.start();} } class God implements Runnable{@Overridepublic void run() {while (true){System.out.println("上帝守護(hù)著你-------");}} } class You implements Runnable{@Overridepublic void run() {for (int i = 0; i <36500 ; i++) {System.out.println("開心著活著每一天------");}System.out.println("----goodbye!Beautiful World!!!------");} }

    線程同步機制

    • 由于同一進(jìn)城的多個線程共享同一塊存儲空間,在帶來方便的同事,也帶來了訪問沖突問題,為了保證數(shù)據(jù)在方法中被訪問時的正確性,在訪問時加入鎖機制synchronized,當(dāng)一個線程獲得對象的排它鎖,獨占資源,其他線程必須等待,使用后釋放鎖即可,存在以下問題:

    • 一個線程持有鎖會導(dǎo)致其它所有需要此鎖的線程掛起;

    • 在多線程競爭下,加鎖,釋放鎖會導(dǎo)致比較多的上下文切換和調(diào)度延時,引起性能問題;

    • 如果一個優(yōu)先級高的線程等待一個優(yōu)先級低的線程釋放鎖,會導(dǎo)致優(yōu)先級倒置,引起性能問題。

    三大不安全案例解決

    不安全的買票

    package com.kuang.demo06; //不安全的買票 public class UnsafeBuyTicket {public static void main(String[] args) {BuyTicket bt=new BuyTicket();new Thread(bt,"我").start();new Thread(bt,"你").start();new Thread(bt,"黃牛黨").start();} }class BuyTicket implements Runnable{//票private int ticketNums=10;boolean flag=true;//外部停止方式@Overridepublic void run() {//買票while (flag){buy();}}public synchronized void buy(){//鎖了方法,相當(dāng)于this 把類給鎖住//判斷是否有票if(ticketNums<=0){System.out.println("票沒了");flag=false;return ; }//模擬延時try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+ticketNums--);} }

    不安全的銀行

    package com.kuang.demo06; //不安全取錢 //兩個人去銀行取錢,賬戶 public class UnsafeBank {public static void main(String[] args) {//賬戶Account account=new Account(100,"結(jié)婚基金");Drawing you=new Drawing(account,50,"你");Drawing girlFriend=new Drawing(account,100,"女朋友");you.start();girlFriend.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;//現(xiàn)在手里又多少錢int nowMoney;public Drawing(Account account,int drawingMoney,String name){super(name);this.account=account;this.drawingMoney=drawingMoney;}//取錢@Overridepublic void run() {synchronized (account) {//鎖的對象是變化的量,鎖需要增刪改的對象//判斷有沒有錢if (account.money - drawingMoney <= 0) {System.out.println(Thread.currentThread().getName() + "錢不夠");return;}//卡內(nèi)余額account.money -= drawingMoney;//手里的錢nowMoney += drawingMoney;System.out.println(account.name + "余額為:" + account.money);//Thread.currentThread().getName()=this.getName();System.out.println(this.getName() + "手里的錢:" + nowMoney);}} }

    用sleep可以放大問題的發(fā)生性

    不安全的集合

    package com.kuang.demo06; import java.util.ArrayList; public class UnsafeList {public static void main(String[] args) {ArrayList<String> list=new ArrayList<String>();for (int i = 0; i <1000 ; i++) {new Thread(()->{synchronized (list){list.add(Thread.currentThread().getName());}}).start();try {Thread.sleep(30);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(list.size());} }

    同步

    同步方法

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-gFDPBjYN-1608708490368)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223135044806.png)]

    同步塊

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-CG6hbeAf-1608708490371)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223135151154.png)]

    死鎖避免方法

    產(chǎn)生死鎖的四個必要條件:

    1.互斥條件:一個資源每次只能被一個進(jìn)程使用。

    2.請求與保持條件:一個進(jìn)程因請求資源而阻塞時,對已獲得的資源保持不妨。

    3.不剝奪條件:進(jìn)程已獲得的資源,在未使用完之前,不能強行剝奪。

    4.循環(huán)等待條件:若干進(jìn)程之間形成一種頭尾相接的循環(huán)等待資源關(guān)系。

    Lock鎖

    • JDK5.0開始,java提供了更強大的線程同步機制——通過顯式定義同步鎖對象來實現(xiàn)同步。同步鎖使用Lock對象充當(dāng)
    • java.util.concurrent.locks.Lock接口是控制多個線程對共享資源進(jìn)行訪問的工具。鎖提供了對共享資源的獨占訪問,每次只能有一個線程對Lock對象加鎖,線程開始訪問共享資源之前應(yīng)先獲得Lock對象
    • ReentrantLock類實現(xiàn)了Lock,它擁有與synchronized相同的并發(fā)性和內(nèi)存語義,在實現(xiàn)線程安全的控制中,比較常用的是ReentrantLock,可以顯式加鎖、釋放鎖。
    package com.kuang.demo06;import java.util.concurrent.locks.ReentrantLock;public class TestLock {public static void main(String[] args) {Ticket ticket = new Ticket();new Thread(ticket).start();new Thread(ticket).start();new Thread(ticket).start();}} class Ticket extends Thread{private int ticketNums=10;//定義lock鎖private final ReentrantLock lock=new ReentrantLock();@Overridepublic void run() {while (true){try {lock.lock();//加鎖if (ticketNums > 0) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(ticketNums--);} else {break;}}finally {lock.unlock();//減鎖}}} }

    synchronized與Lock的對比

    • Lock是顯式鎖(手動開啟和關(guān)閉鎖,別忘記關(guān)閉鎖)synchronized是隱式鎖,出了作用域自動釋放
    • Lock只有 代碼塊加鎖 ,synchronized有代碼塊鎖和方法鎖
    • 使用Lock鎖,JVM將花費較少的時間來調(diào)度線程,性能更好。并且具有更好的擴展性(提供更多的子類)
    • 優(yōu)先使用順序:
    • Lock>同步代碼塊(已經(jīng)進(jìn)入了方法體,分配了相應(yīng)資源)>同步方法(在方法體之外)

    線程通信

    案例:生產(chǎn)者消費者

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-978jJ3Gl-1608708490372)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223142705516.png)]

    • 假設(shè)倉庫中只能存放一件產(chǎn)品,生產(chǎn)者將生產(chǎn)出來的產(chǎn)品放入倉庫,消費者將倉庫中產(chǎn)品取走消費。
    • 如果倉庫中沒有產(chǎn)品,則生產(chǎn)者將產(chǎn)品放入倉庫,否則停止生產(chǎn)并等待,直到倉庫中的產(chǎn)品被消費者取走為止。
    • 如果倉庫中放有產(chǎn)品,則消費者可以將產(chǎn)品取走消費,否則停止消費并等待,直到倉庫中再次放入產(chǎn)品為止。

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-35X9RRsH-1608708490374)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223142745865.png)]

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-KfXsnaeX-1608708490376)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223142856572.png)]

    管程法

    package com.kuang.demo07; //測試:生產(chǎn)者消費者模型--》 //生產(chǎn)者,消費者,產(chǎn)品 public class TestPC{public static void main(String[] args) {SynContain contain=new SynContain();new Productor(contain).start();new Consumer(contain).start();}}//生產(chǎn)者 class Productor extends Thread{SynContain contain;public Productor(SynContain contain){this.contain=contain;}@Override//生產(chǎn)public void run(){for (int i = 0; i < 100; i++) {contain.push(new Chicken(i));System.out.println("生產(chǎn)了"+i+"只雞");}} }//消費者 class Consumer extends Thread{SynContain contain;public Consumer(SynContain contain){this.contain=contain;}@Override//生產(chǎn)public void run(){for (int i = 0; i < 100; i++) {System.out.println("消費了"+contain.pop().id+"只雞");}}} //產(chǎn)品 class Chicken{int id;//產(chǎn)品編public Chicken(int id){this.id=id; }} //容器 class SynContain {//需要一個容器大小Chicken[] chickens = new Chicken[10];//容器計數(shù)器int count = 0;//生產(chǎn)者放入產(chǎn)品public synchronized void push(Chicken chicken) {//如果容器滿了,需要等待消費者消費if (count == chickens.length) {//通知消費者消費.生產(chǎn)等待try {//Ctrl加Alt加T進(jìn)行代碼塊的包裹this.wait();} catch (InterruptedException e) {e.printStackTrace();}}//如果沒有滿,我們就需要丟入產(chǎn)品chickens[count] = chicken;count++;//可以同知消費this.notifyAll();}//消費者消費產(chǎn)品public synchronized Chicken pop() {//判斷能否消費if (count == 0) {//等待生產(chǎn)者生產(chǎn),消費者等待try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}//如果可以消費count--;Chicken chicken = chickens[count];//吃完了,通知生產(chǎn)者生產(chǎn)this.notifyAll();return chicken;}}

    信號燈法

    package com.kuang.demo07; public class TestPc2 {public static void main(String[] args) {TV tv = new TV();new Player(tv).start();new Watcher(tv).start();} } //生產(chǎn)者--》演員 class Player extends Thread{TV tv;public Player(TV tv) {this.tv = tv;}@Overridepublic void run() {for (int i = 0; i <20 ; i++) {if (i%2==0){this.tv.play("快樂大本營播放中");}else{this.tv.play("抖音:記錄美好生活");}}} } //消費者--》觀眾 class Watcher extends Thread{TV tv;public Watcher(TV tv) {this.tv = tv;}@Overridepublic void run() {for (int i = 0; i <20 ; i++) {tv.watch();}} } //產(chǎn)品-->節(jié)目 class TV{//演員表演,觀眾等待 T//觀眾觀看,演員等待 FString voice;//表演的節(jié)目boolean flag=true;//表演public synchronized void play(String voice){if (!flag){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("演員表演了:"+voice);//通知觀眾觀看this.notifyAll();//通知喚醒this.voice=voice;this.flag=!this.flag;}//觀看public synchronized void watch(){if (flag){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("觀看了:"+voice);//同知演員表演this.notifyAll();this.flag=!this.flag;} }

    線程池

    [外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-4gsVZkGS-1608708490376)(C:\Users\王東梁\AppData\Roaming\Typora\typora-user-images\image-20201223151328767.png)]

    • 背景:經(jīng)常創(chuàng)建和銷毀、使用量特別大的資源,比如并發(fā)情況下的線程,對性能影響很大。
    • 思路:提前創(chuàng)建好多個線程,放入線程池中,使用時直接獲取,使用完放回池中。可以避免頻繁創(chuàng)建銷毀、實現(xiàn)重復(fù)利用。類似生活中的公共交通工具。
    • 好處:
      • 提高響應(yīng)速度(減少了創(chuàng)建新線程的時間)
      • 降低資源消耗(重復(fù)利用線程池中線程,不需要每次都創(chuàng)建)
      • 便于線程管理(。。。)
        • corePoolSize:核心池的大小
        • maximumPoolSize:最大線程數(shù)
        • keepAliveTime:線程沒有任務(wù)時最多保持多長時間后會終止
    package com.kuang.demo07; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class TestPool {public static void main(String[] args) {//1.創(chuàng)建服務(wù),創(chuàng)建線程池ExecutorService service= Executors.newFixedThreadPool(10);//newFixedThreadPool 參數(shù)為:線程池大小//執(zhí)行service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());service.execute(new MyThread());//2.關(guān)閉連接service.shutdown();} } class MyThread implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName());} }

    總結(jié)

    以上是生活随笔為你收集整理的JAVA多线程总结(笔记)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。