多執行緒核心知識總結
趣解Thread和Object類中的執行緒相關方法
方法概覽
wait,notify,notifyAll 的作用和方法
阻塞階段
四種情況下會被喚醒
- 另一個執行緒呼叫這個物件的notify()方法且剛好被喚醒的是本執行緒,
- 另一個執行緒呼叫這個物件的notifyAll()
- 過了wait(long timeout)規定的超時時間,如果傳入0就是永久等待,
- 執行緒自身呼叫了interrupt()
喚醒階段
notify會喚醒單個正在等待某物件monitor的執行緒,如果有多個執行緒都在等待,它只會喚醒一個,具體喚醒的選擇是任意的,java對此沒有明確規范,JVM可以擁有自己的實作,對此有一定的自由裁量權,而notify和wait都得在synchronize保護的代碼塊或者方法中執行
/**
* 描述: 展示wait和notify的基本用法 1. 研究代碼執行順序 2. 證明wait釋放鎖
*/
public class Wait {
public static Object object = new Object();
static class Thread1 extends Thread {
@Override
public void run() {
synchronized (object) {
System.out.println(Thread.currentThread().getName() + "開始執行了");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("執行緒" + Thread.currentThread().getName() + "獲取到了鎖,");
}
}
}
static class Thread2 extends Thread {
@Override
public void run() {
synchronized (object) {
object.notify();
System.out.println("執行緒" + Thread.currentThread().getName() + "呼叫了notify()");
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.start();
Thread.sleep(200);
thread2.start();
}
}
/**
* 描述: 3個執行緒,執行緒1和執行緒2首先被阻塞,執行緒3喚醒它們,notify, notifyAll, start先執行不代表執行緒先啟動,
*/
public class WaitNotifyAll implements Runnable {
private static final Object resourceA = new Object();
public static void main(String[] args) throws InterruptedException {
Runnable r = new WaitNotifyAll();
Thread threadA = new Thread(r);
Thread threadB = new Thread(r);
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
resourceA.notifyAll();
// resourceA.notify();
System.out.println("ThreadC notified.");
}
}
});
threadA.start();
threadB.start();
// Thread.sleep(200);
threadC.start();
}
@Override
public void run() {
synchronized (resourceA) {
System.out.println(Thread.currentThread().getName()+" got resourceA lock.");
try {
System.out.println(Thread.currentThread().getName()+" waits to start.");
resourceA.wait();
System.out.println(Thread.currentThread().getName()+"'s waiting to end.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
1. 描述: 證明wait只釋放當前的那把鎖
*/
public class WaitNotifyReleaseOwnMonitor {
private static volatile Object resourceA = new Object();
private static volatile Object resourceB = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("ThreadA got resourceA lock.");
synchronized (resourceB) {
System.out.println("ThreadA got resourceB lock.");
try {
System.out.println("ThreadA releases resourceA lock.");
resourceA.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (resourceA) {
System.out.println("ThreadB got resourceA lock.");
System.out.println("ThreadB tries to resourceB lock.");
synchronized (resourceB) {
System.out.println("ThreadB got resourceB lock.");
}
}
}
});
thread1.start();
thread2.start();
}
}
wait notify,notifyAll的特點和性質
- 用必須先擁有monitor
- 只能喚醒其中一個
- 屬于Object類
- 類似功能的Condition
- 同時持有多個鎖的情況 :只會釋放現在找到個wait()對應物件的那把鎖,
wait原理
Entry Set 入口集
Wait Set 等待集

生產者消費者設計模式
/**
* 描述: 用wait/notify來實作生產者消費者模式
*/
public class ProducerConsumerModel {
public static void main(String[] args) {
EventStorage eventStorage = new EventStorage();
Producer producer = new Producer(eventStorage);
Consumer consumer = new Consumer(eventStorage);
new Thread(producer).start();
new Thread(consumer).start();
}
}
class Producer implements Runnable {
private EventStorage storage;
public Producer(
EventStorage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
storage.put();
}
}
}
class Consumer implements Runnable {
private EventStorage storage;
public Consumer(
EventStorage storage) {
this.storage = storage;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
storage.take();
}
}
}
class EventStorage {
private int maxSize;
private LinkedList<Date> storage;
public EventStorage() {
maxSize = 10;
storage = new LinkedList<>();
}
public synchronized void put() {
while (storage.size() == maxSize) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
storage.add(new Date());
System.out.println("倉庫里有了" + storage.size() + "個產品,");
notify();
}
public synchronized void take() {
while (storage.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("拿到了" + storage.poll() + ",現在倉庫還剩下" + storage.size());
notify();
}
}
wait,notify常見面試問題
用程式實作兩個執行緒交替列印0~100的奇偶數
基本思路 synchronize
/**
* 描述: 兩個執行緒交替列印0~100的奇偶數,用synchronized關鍵字實作
*/
public class WaitNotifyPrintOddEvenSyn {
private static int count;
private static final Object lock = new Object();
//新建2個執行緒
//1個只處理偶數,第二個只處理奇數(用位運算)
//用synchronized來通信
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if ((count & 1) == 0) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
}, "偶數").start();
new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if ((count & 1) == 1) {
System.out.println(Thread.currentThread().getName() + ":" + count++);
}
}
}
}
}, "奇數").start();
}
}
用wait和notify減少廢操作
/**
* 描述: 兩個執行緒交替列印0~100的奇偶數,用wait和notify
*/
public class WaitNotifyPrintOddEveWait {
private static int count = 0;
private static final Object lock = new Object();
public static void main(String[] args) {
new Thread(new TurningRunner(), "偶數").start();
new Thread(new TurningRunner(), "奇數").start();
}
//1. 拿到鎖,我們就列印
//2. 列印完,喚醒其他執行緒,自己就休眠
static class TurningRunner implements Runnable {
@Override
public void run() {
while (count <= 100) {
synchronized (lock) {
//拿到鎖就列印
System.out.println(Thread.currentThread().getName() + ":" + count++);
lock.notify();
if (count <= 100) {
try {
//如果任務還沒結束,就讓出當前的鎖,并休眠
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
手寫生產者消費者設計模式
上文已寫
為什么wait()需要在同步代碼塊使用而sleep()不需要
為了讓通信變得可靠,防止死鎖和永久等待的發生,因為如果我們不把wait和notify都放在代碼塊里面的話,那么很有可能是執行wait之前,執行緒突然切換,切換到具有notify的一個執行緒,因為沒有synchronize保護,隨時都可以切過去,這樣對面的第二個執行緒就吧程式執行完畢了,會導致進入wait()后,沒有notify能喚醒,就會永久等待或者死鎖,而sleep不存在這樣的問題,
為什么執行緒通信的方法wait(),notify(),notifyAll()被定義在Object里面,而sleep定義在Thread里面
因為wait(),notify(),notifyAll(),是鎖級別的操作,而鎖是屬于某個物件的,所以這三個方法被定義在Object里面,
wait方法是屬于Object物件的,那呼叫Thread.wait()會怎么樣?
Thread也是繼承Object的,但是對于Thread類很特殊,執行緒退出時會自動呼叫notify(),這樣設計的整個流程都會受到影響,
notifyAll后,所有執行緒都去再次搶奪鎖,如果某執行緒搶奪失敗會如何
沒有搶到鎖的執行緒會進行等待,直到拿到鎖,
sleep方法詳解
作用:讓執行緒在預期的時間執行,其他時候不要占用CPU資源
sleep方法不釋放鎖:
- 包括synchrinized 和 lock
- 和wait不同
/**
1. 展示執行緒sleep的時候不釋放synchronized的monitor,等sleep時間到了以后,正常結束后才釋放鎖
*/
public class SleepDontReleaseMonitor implements Runnable {
public static void main(String[] args) {
SleepDontReleaseMonitor sleepDontReleaseMonitor = new SleepDontReleaseMonitor();
new Thread(sleepDontReleaseMonitor).start();
new Thread(sleepDontReleaseMonitor).start();
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
System.out.println("執行緒" + Thread.currentThread().getName() + "獲取到了monitor,");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("執行緒" + Thread.currentThread().getName() + "退出了同步代碼塊");
}
}
sleep方法回應中斷
- 拋出InterruptedException
- 清除中斷狀態
/**
* 描述: 每個1秒鐘輸出當前時間,被中斷,觀察,
* Thread.sleep()
* TimeUnit.SECONDS.sleep()
*/
public class SleepInterrupted implements Runnable{
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new SleepInterrupted());
thread.start();
Thread.sleep(6500);
thread.interrupt();
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(new Date());
try {
TimeUnit.HOURS.sleep(3);
TimeUnit.MINUTES.sleep(25);
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("我被中斷了!");
e.printStackTrace();
}
}
}
}
sleep方法可以讓執行緒進入Waiting狀態,并且不占用CPU資源,但是不釋放鎖,直到規定時間后再執行,休眠期間如果被中斷,會拋出例外并清除中斷狀態,
sleep常見面試問題
sleep,wait/nofity異同(方法屬于哪個物件?執行緒狀態怎么切換?)
-
相同
阻塞:都會讓執行緒進入阻塞狀態
回應中斷:即使休眠期間也會回應中斷,拋出例外 -
不同
同步方法中:wait和notify必須在同步方法中執行(執行緒安全,防止死鎖和永久等待),sleep不需要
釋放鎖: wait會釋放鎖,sleep不會
指定時間:sleep必須傳參,wait如果不傳參會直到自己被喚醒,
所屬類
join 方法詳解
- 作用:因為新的執行緒加入了我們,所以我們要等他執行完再出發
- 用法: main等待thread1執行完畢,注意誰等誰
- 普通用法:
/**
* 描述: 演示join,注意陳述句輸出順序,會變化,
*/
public class Join {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "執行完畢");
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "執行完畢");
}
});
thread.start();
thread2.start();
System.out.println("開始等待子執行緒運行完畢");
thread.join();
thread2.join();
System.out.println("所有子執行緒執行完畢");
}
}
join注意點
CountDownLatch 或CyclicBarrier類
相同效果的實作類
join原理
原始碼:
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
寫出join的替代方法
/**
* 描述: 通過了解join原理,分析出join的代替寫法
*/
public class JoinPrinciple {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "執行完畢");
}
});
thread.start();
System.out.println("開始等待子執行緒運行完畢");
thread.join();
// synchronized (thread) {
// thread.wait();
// }
System.out.println("所有子執行緒執行完畢");
}
}
join常見面試問題
在join期間,執行緒處于哪種執行緒狀態?
join期間執行緒會處于waiting的狀態
yield方法詳解
- 作用:釋放我的CPU時間片
- 定位:JVM不保證遵循
- yield和sleep區別:是否隨時可能再次被調度 sleep期間被阻塞,yield只是暫時將調度權讓出
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/181365.html
標籤:其他
