【學習】003多線程之間實現通訊
課程目標
多線程之間如何通訊
wait、notify、notifyAll()方法
lock
停止線程
多線程之間如何實現通訊
什麽是多線程之間通訊?
多線程之間通訊,其實就是多個線程在操作同一個資源,但是操作的動作不同。
畫圖演示
多線程之間通訊需求
需求:第一個線程寫入(input)用戶,另一個線程取讀取(out)用戶.實現讀一個,寫一個操作。
代碼實現基本實現
共享資源源實體類
package hongmoshui.com.cnblogs.www.study.day003; /** * 共享資源源實體類 * @author 洪墨水*/ class Res { public String userSex; public String userName; }
輸入線程資源
/** * 輸入線程資源 * @author 洪墨水 */ class IntThrad extends Thread { private Res res; public IntThrad(Res res) { this.res = res; } @Override public void run() {int count = 0; while (true) { if (count == 0) { res.userName = "余勝軍"; res.userSex = "男"; } else { res.userName = "小紅"; res.userSex = "女"; } count= (count + 1) % 2; } } }
輸出線程
/** * 輸出線程 * @author 洪墨水 */ class OutThread extends Thread { private Res res; public OutThread(Res res) { this.res = res; } @Override public void run() { while (true) { System.out.println(res.userName + "--" + res.userSex); } } }
運行代碼
/** * 運行代碼 * @author 洪墨水 */ public class Demo1 { public static void main(String[] args) { Res res = new Res(); IntThrad intThrad = new IntThrad(res); OutThread outThread = new OutThread(res); intThrad.start(); outThread.start(); } }
運行結果
註意:數據發生錯亂,造成線程安全問題
解決線程安全問題
IntThrad 加上synchronized
class IntThrad2 extends Thread { private Res res; public IntThrad2(Res res) { this.res = res; } @Override public 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; } } } }
輸出線程加上synchronized
package hongmoshui.com.cnblogs.www.study.day003; class Res2 { public String userName; public String sex; } class InputThread extends Thread { private Res2 res2; public InputThread(Res2 res2) { this.res2 = res2; } @Override public void run() { int count = 0; while (true) { synchronized (res2) { if (count == 0) { res2.userName = "余勝軍"; res2.sex = "男"; } else { res2.userName = "小紅"; res2.sex = "女"; } count = (count + 1) % 2; } } } } class OutThrad extends Thread { private Res2 res2; public OutThrad(Res2 res2) { this.res2 = res2; } @Override public void run() { while (true) { synchronized (res2) { System.out.println(res2.userName + "," + res2.sex); } } } } /** * 輸出線程加上synchronized * @author 洪墨水 */ public class ThreadDemo01 { public static void main(String[] args) { Res2 res2 = new Res2(); InputThread inputThread = new InputThread(res2); OutThrad outThrad = new OutThrad(res2); inputThread.start(); outThrad.start(); } }
wait()、notify、notifyAll()方法
wait()、notify()、notifyAll()是三個定義在Object類裏的方法,可以用來控制線程的狀態。
這三個方法最終調用的都是jvm級的native方法。隨著jvm運行平臺的不同可能有些許差異。
如果對象調用了wait方法就會使持有該對象的線程把該對象的控制權交出去,然後處於等待狀態。
如果對象調用了notify方法就會通知某個正在等待這個對象的控制權的線程可以繼續運行。
如果對象調用了notifyAll方法就會通知所有等待這個對象控制權的線程繼續運行。
註意:一定要在線程同步中使用,並且是同一個鎖的資源
package hongmoshui.com.cnblogs.www.study.day003; class Res3 { public String userSex; public String userName; // 線程通訊標識 public boolean flag = false; } class IntThrad3 extends Thread { private Res3 res3; public IntThrad3(Res3 res3) { this.res3 = res3; } @Override public void run() { int count = 0; while (true) { synchronized (res3) { if (res3.flag) { try { // 當前線程變為等待,但是可以釋放鎖 res3.wait(); } catch (Exception e) { } } if (count == 0) { res3.userName = "余勝軍"; res3.userSex = "男"; } else { res3.userName = "小紅"; res3.userSex = "女"; } count = (count + 1) % 2; res3.flag = true; // 喚醒當前線程 res3.notify(); } } } } class OutThread3 extends Thread { private Res3 res3; public OutThread3(Res3 res3) { this.res3 = res3; } @Override public void run() { while (true) { synchronized (res3) { if (!res3.flag) { try { res3.wait(); } catch (Exception e) { // TODO: handle exception } } System.out.println(res3.userName + "--" + res3.userSex); res3.flag = false; res3.notify(); } } } } public class ThreaCommun { public static void main(String[] args) { Res3 res3 = new Res3(); IntThrad3 intThrad3 = new IntThrad3(res3); OutThread3 outThread3 = new OutThread3(res3); intThrad3.start(); outThread3.start(); } }
wait與sleep區別?
對於sleep()方法,我們首先要知道該方法是屬於Thread類中的。而wait()方法,則是屬於Object類中的。
sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。
在調用sleep()方法的過程中,線程不會釋放對象鎖。
而當調用wait()方法的時候,線程會放棄對象鎖,進入等待此對象的等待鎖定池,只有針對此對象調用notify()方法後本線程才進入對象鎖定池準備
獲取對象鎖進入運行狀態。
JDK1.5-Lock
在 jdk1.5 之後,並發包中新增了 Lock 接口(以及相關實現類)用來實現鎖功能,Lock 接口提供了與 synchronized 關鍵字類似的同步功能,但需要在使用時手動獲取鎖和釋放鎖。
Lock寫法
Lock lock = new ReentrantLock(); lock.lock(); try { // 可能會出現線程安全的操作 } finally { // 一定在finally中釋放鎖 // 也不能把獲取鎖在try中進行,因為有可能在獲取鎖的時候拋出異常 lock.unlock(); }
Lock 接口與 synchronized 關鍵字的區別
Lock 接口可以嘗試非阻塞地獲取鎖 當前線程嘗試獲取鎖。如果這一時刻鎖沒有被其他線程獲取到,則成功獲取並持有鎖。
Lock 接口能被中斷地獲取鎖 與 synchronized 不同,獲取到鎖的線程能夠響應中斷,當獲取到的鎖的線程被中斷時,中斷異常將會被拋出,同時鎖會被釋放。
Lock 接口在指定的截止時間之前獲取鎖,如果截止時間到了依舊無法獲取鎖,則返回。
Condition用法
Condition的功能類似於在傳統的線程技術中的,Object.wait()和Object.notify()的功能。
代碼
Condition condition = lock.newCondition();
res. condition.await(); 類似wait
res. Condition. Signal() 類似notify
package hongmoshui.com.cnblogs.www.study.day003; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class Res4 { public String userName; public String sex; public boolean flag = false; Lock lock = new ReentrantLock(); } class InputThread4 extends Thread { private Res4 res4; Condition newCondition; public InputThread4(Res4 res4, Condition newCondition) { this.res4 = res4; this.newCondition = newCondition; } @Override public void run() { int count = 0; while (true) { // synchronized (res4) { try { res4.lock.lock(); if (res4.flag) { try { // res4.wait(); newCondition.await(); } catch (Exception e) { // TODO: handle exception } } if (count == 0) { res4.userName = "余勝軍"; res4.sex = "男"; } else { res4.userName = "小紅"; res4.sex = "女"; } count = (count + 1) % 2; res4.flag = true; // res4.notify(); newCondition.signal(); } catch (Exception e) { // TODO: handle exception } finally { res4.lock.unlock(); } } // } } } class OutThrad4 extends Thread { private Res4 res4; private Condition newCondition; public OutThrad4(Res4 res4, Condition newCondition) { this.res4 = res4; this.newCondition = newCondition; } @Override public void run() { while (true) { // synchronized (res4) { try { res4.lock.lock(); if (!res4.flag) { try { // res4.wait(); newCondition.await(); } catch (Exception e) { // TODO: handle exception } } System.out.println(res4.userName + "," + res4.sex); res4.flag = false; // res4.notify(); newCondition.signal(); } catch (Exception e) { // TODO: handle exception } finally { res4.lock.unlock(); } // } } } } public class ThreadDemo02 { public static void main(String[] args) { Res4 res4 = new Res4(); Condition newCondition = res4.lock.newCondition(); InputThread4 inputThread4 = new InputThread4(res4, newCondition); OutThrad4 outThrad4 = new OutThrad4(res4, newCondition); inputThread4.start(); outThrad4.start(); } }
如何停止線程?
停止線程思路
1. 使用退出標誌,使線程正常退出,也就是當run方法完成後線程終止。
2. 使用stop方法強行終止線程(這個方法不推薦使用,因為stop和suspend、resume一樣,也可能發生不可預料的結果)。
3. 使用interrupt方法中斷線程。
代碼:
package hongmoshui.com.cnblogs.www.study.day003; class StopThread implements Runnable { private boolean flag = true; @Override public synchronized void run() { while (flag) { try { wait(); } catch (Exception e) { // e.printStackTrace(); stopThread(); } System.out.println("thread run.."); } } /** * * 停止線程 * @author: 洪墨水 */ public void stopThread() { flag = false; } } /** * * 停止線程 * @author: 洪墨水 */ 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++; } } }
ThreadLocal
什麽是ThreadLocal
ThreadLocal提高一個線程的局部變量,訪問某個線程擁有自己局部變量。
當使用ThreadLocal維護變量時,ThreadLocal為每個使用該變量的線程提供獨立的變量副本,所以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。
ThreadLocal的接口方法
ThreadLocal類接口很簡單,只有4個方法,我們先來了解一下:
- void set(Object value)設置當前線程的線程局部變量的值。
- public Object get()該方法返回當前線程所對應的線程局部變量。
- public void remove()將當前線程局部變量的值刪除,目的是為了減少內存的占用,該方法是JDK 5.0新增的方法。需要指出的是,當線程結束後,對應該線程的局部變量將自動被垃圾回收,所以顯式調用該方法清除線程的局部變量並不是必須的操作,但它可以加快內存回收的速度。
- protected Object initialValue()返回該線程局部變量的初始值,該方法是一個protected的方法,顯然是為了讓子類覆蓋而設計的。這個方法是一個延遲調用方法,在線程第1次調用get()或set(Object)時才執行,並且僅執行1次。ThreadLocal中的缺省實現直接返回一個null。
案例:創建三個線程,每個線程生成自己獨立序列號。
代碼:
package hongmoshui.com.cnblogs.www.study.day003; class Res5 { // 生成序列號共享變量 public static Integer count = 0; public static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() { protected Integer initialValue() { return 0; }; }; public Integer getNum() { int count = threadLocal.get() + 1; threadLocal.set(count); return count; } } /** * 創建三個線程,每個線程生成自己獨立序列號 * @author 洪墨水 */ public class ThreadLocaDemo3 extends Thread { private Res5 res5; public ThreadLocaDemo3(Res5 res5) { this.res5 = res5; } @Override public void run() { for (int i = 0; i < 3; i++) { System.out.println(Thread.currentThread().getName() + "---" + "i---" + i + "--num:" + res5.getNum()); } } public static void main(String[] args) { Res5 res5 = new Res5(); ThreadLocaDemo3 threadLocaDemo1 = new ThreadLocaDemo3(res5); ThreadLocaDemo3 threadLocaDemo2 = new ThreadLocaDemo3(res5); ThreadLocaDemo3 threadLocaDemo3 = new ThreadLocaDemo3(res5); threadLocaDemo1.start(); threadLocaDemo2.start(); threadLocaDemo3.start(); } }
ThreadLocal實現原理
ThreadLocal通過map集合
Map.put(“當前線程”,值);
【學習】003多線程之間實現通訊