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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java多线程有几种实现方法_Java多线程之间实现通讯

發布時間:2025/3/19 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java多线程有几种实现方法_Java多线程之间实现通讯 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、課程目標

多線程之間如何通訊

wait、notify、notifyAll()方法

lock

停止線程

守護線程

Join方法

優先級

Yield

二、多線程之間如何實現通訊

2.1 什么是多線程之間通訊?

多線程之間通訊,其實就是多個線程在操作同一個資源,但是操作的動作不同。

畫圖演示

2.2 多線程之間通訊需求

需求:第一個線程寫入(input)用戶,另一個線程取讀取(out)用戶.實現讀一個,寫一個操作。

2.3代碼實現基本實現

2.3.1共享資源源實體類

class Res {

public String userSex;

public String userName;

}

2.3.2輸入線程資源

class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {if (count == 0) {res.userName = "余勝軍";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;}}}

2.3.3輸出線程

class OutThread extends Thread {private Res res;public OutThread(Res res) {this.res = res;}@Overridepublic void run() {while (true) {System.out.println(res.userName + "--" + res.userSex);}}}

2.3.4運行代碼

Res res = new Res();IntThrad intThrad = new IntThrad(res);OutThread outThread = new OutThread(res);intThrad.start();outThread.start();

2.3.5運行代碼

注意:數據發生錯亂,造成線程安全問題

2.3.6解決線程安全問題

2.3.6.1 IntThrad 加上synchronized

class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {synchronized (res) {if (count == 0) {res.userName = "余勝軍";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;}}}}

2.3.6.2 輸出線程加上synchronized

class OutThread extends Thread {private Res res;public OutThread(Res res) {this.res = res;}@Overridepublic void run() {while (true) {synchronized (res) {System.out.println(res.userName + "--" + res.userSex);}}}}

2.4 wait()、notify、notifyAll()方法

wait()、notify()、notifyAll()是三個定義在Object類里的方法,可以用來控制線程的狀態。

這三個方法最終調用的都是jvm級的native方法。隨著jvm運行平臺的不同可能有些許差異。

?如果對象調用了wait方法就會使持有該對象的線程把該對象的控制權交出去,然后處于等待狀態。

?如果對象調用了notify方法就會通知某個正在等待這個對象的控制權的線程可以繼續運行。

如果對象調用了notifyAll方法就會通知所有等待這個對象控制權的線程繼續運行。

class Res {public String userSex;public String userName;//線程通訊標識public boolean flag = false;}class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {synchronized (res) {if (res.flag) {try { // 當前線程變為等待,但是可以釋放鎖res.wait();} catch (Exception e) {}}if (count == 0) {res.userName = "余勝軍";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;res.flag = true;// 喚醒當前線程res.notify();}}}}class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {synchronized (res) {if (res.flag) {try { // 當前線程變為等待,但是可以釋放鎖res.wait();} catch (Exception e) {}}if (count == 0) {res.userName = "余勝軍";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;res.flag = true;// 喚醒當前線程res.notify();}}}}public class ThreaCommun {public static void main(String[] args) {Res res = new Res();IntThrad intThrad = new IntThrad(res);OutThread outThread = new OutThread(res);intThrad.start();outThread.start();}}

2.5 wait與sleep區別?

對于sleep()方法,我們首先要知道該方法是屬于Thread類中的。而wait()方法,則是屬于Object類中的。

sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。

在調用sleep()方法的過程中,線程不會釋放對象鎖。

而當調用wait()方法的時候,線程會放棄對象鎖,進入等待此對象的等待鎖定池,只有針對此對象調用notify()方法后本線程才進入對象鎖定池準備

獲取對象鎖進入運行狀態。

三、JDK1.5-Lock

在 jdk1.5 之后,并發包中新增了 Lock 接口(以及相關實現類)用來實現鎖功能,Lock 接口提供了與 synchronized 關鍵字類似的同步功能,但需要在使用時手動獲取鎖和釋放鎖。

3.1 、Lock寫法:

Lock lock = new ReentrantLock();lock.lock();try{//可能會出現線程安全的操作}finally{//一定在finally中釋放鎖//也不能把獲取鎖在try中進行,因為有可能在獲取鎖的時候拋出異常 lock.ublock();}

3.2 、ReentrantLock寫法:

ReentrantLock是一個可重入的互斥鎖,ReentrantLock由最近成功獲取鎖,還沒有釋放的線程所擁有,當鎖被另一個線程擁有時,調用lock的線程可以成功獲取鎖。如果鎖已經被當前線程擁有,當前線程會立即返回

3.3、Lock 接口與 synchronized 關鍵字的區別

Lock 接口可以嘗試非阻塞地獲取鎖 當前線程嘗試獲取鎖。如果這一時刻鎖沒有被其他線程獲取到,則成功獲取并持有鎖。

*Lock 接口能被中斷地獲取鎖 與 synchronized 不同,獲取到鎖的線程能夠響應中斷,當獲取到的鎖的線程被中斷時,中斷異常將會被拋出,同時鎖會被釋放。

Lock 接口在指定的截止時間之前獲取鎖,如果截止時間到了依舊無法獲取鎖,則返回。

3.4、Condition用法

Condition的功能類似于在傳統的線程技術中的,Object.wait()和Object.notify()的功能,

代碼:

Condition condition = lock.newCondition();res. condition.await(); 類似waitres. Condition. Signal() 類似notifySignalall notifyALL

四、如何停止線程?

4.1 停止線程思路

  • 使用退出標志,使線程正常退出,也就是當run方法完成后線程終止。
  • 使用stop方法強行終止線程(這個方法不推薦使用,因為stop和suspend、resume一樣,也可能發生不可預料的結果)。
  • 使用interrupt方法中斷線程。 線程在阻塞狀態
  • 代碼:

    class StopThread implements Runnable {private boolean flag = true;@Overridepublic synchronized void run() {while (flag) {try {wait();} catch (Exception e) {//e.printStackTrace();stopThread();}System.out.println("thread run..");}}public void stopThread() {flag = false;}}public class StopThreadDemo {public static void main(String[] args) {StopThread stopThread1 = new StopThread();Thread thread1 = new Thread(stopThread1);Thread thread2 = new Thread(stopThread1);thread1.start();thread2.start();int i = 0;while (true) {System.out.println("thread main..");if (i == 300) {// stopThread1.stopThread();thread1.interrupt();thread2.interrupt();break;}i++;}}}

    五、守護線程

    Java中有兩種線程,一種是用戶線程,另一種是守護線程。

    當進程不存在或主線程停止,守護線程也會被停止。

    使用setDaemon(true)方法設置為守護線程

    public class DaemonThread {public static void main(String[] args) {Thread thread = new Thread(new Runnable() {@Overridepublic void run() {while (true) {try {Thread.sleep(100);} catch (Exception e) {// TODO: handle exception}System.out.println("我是子線程...");}}});thread.setDaemon(true);thread.start();for (int i = 0; i < 10; i++) {try {Thread.sleep(100);} catch (Exception e) {}System.out.println("我是主線程");}System.out.println("主線程執行完畢!");}}

    六、join()方法作用

    join作用是讓其他線程變為等待

    6.1需求:

    創建一個線程,子線程執行完畢后,主線程才能執行。

    class JoinThread implements Runnable {

    public void run() {

    for (int i = 0; i < 100; i++) {

    System.out.println(Thread.currentThread().getName() + "---i:" + i);

    }

    }

    }

    class JoinThread implements Runnable {

    public void run() {

    for (int i = 0; i < 100; i++) {

    System.out.println(Thread.currentThread().getName() + "---i:" + i);

    }

    }

    }

    七、優先級

    現代操作系統基本采用時分的形式調度運行的線程,線程分配得到的時間片的多少決定了線程使用處理器資源的多少,也對應了線程優先級這個概念。在JAVA線程中,通過一個int priority來控制優先級,范圍為1-10,其中10最高,默認值為5。下面是源碼(基于1.8)中關于priority的一些量和方法。

    class PrioritytThread implements Runnable {public void run() {for (int i = 0; i < 100; i++) {System.out.println(Thread.currentThread().toString() + "---i:" + i);}}}public class ThreadDemo4 {public static void main(String[] args) {PrioritytThread prioritytThread = new PrioritytThread();Thread t1 = new Thread(prioritytThread);Thread t2 = new Thread(prioritytThread);t1.start();// 注意設置了優先級, 不代表每次都一定會被執行。 只是CPU調度會有限分配t1.setPriority(10);t2.start();}}

    八、Yield方法

    Thread.yield()方法的作用:暫停當前正在執行的線程,并執行其他線程。(可能沒有效果)

    yield()讓當前正在運行的線程回到可運行狀態,以允許具有相同優先級的其他線程獲得運行的機會。因此,使用yield()的目的是讓具有相同優先級的線程之間能夠適當的輪換執行。但是,實際中無法保證yield()達到讓步的目的,因為,讓步的線程可能被線程調度程序再次選中。

    結論:大多數情況下,yield()將導致線程從運行狀態轉到可運行狀態,但有可能沒有效果。

    九、練習題

    9.1有T1、T2、T3三個線程,如何怎樣保證T2在T1執行完后執行,T3在T2執行完后執行?

    總結

    以上是生活随笔為你收集整理的java多线程有几种实现方法_Java多线程之间实现通讯的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。