package com.hencoder.a17_thread_interaction;
/**
* 讀寫鎖。
* ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
* Lock readLock = lock.readLock();
* Lock writeLock = lock.writeLock();
*
*/
public class WaitDemo implements TestDemo {
private String sharedString;
private int x=0;
private int y=0;
/**
* synchronized 關(guān)鍵字是鎖定當(dāng)前的對(duì)象。
* 被synchronized包括的代碼塊將會(huì)是一個(gè)原子性的操作,中間不會(huì)被打斷
*/
public synchronized void add(){
//x++ 在cpu中是分為以下兩個(gè)步驟來執(zhí)行的
//int tmep = x + 1;
//x = temp;
x++;
y++;
}
public void sub(){
synchronized (this){//這個(gè) 等價(jià)于 直接在方法上面加synchronized 關(guān)鍵字
x--;
y--;
}
}
private synchronized void initString() {
sharedString = "rengwuxian";
notifyAll();//必須寫在synchronized方法里
}
private synchronized void printString() {
//wait()方法 會(huì)暫時(shí)丟掉synchronized鎖。直到InterruptedException或者 notify
while (sharedString == null) {//要用while因?yàn)?Thread.interrupted()也會(huì)喚醒wait();
try {
wait();//必須寫在synchronized方法里,因?yàn)閣ait要釋放鎖
} catch (InterruptedException e) {//如果線程被調(diào)用了Thread.interrupted()方法 則會(huì)拋出這個(gè)異常
e.printStackTrace();
}
}
System.out.println("String: " + sharedString);
}
@Override
public void runTest() {
final Thread thread1 = new Thread() {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
printString();
}
};
thread1.start();
Thread thread2 = new Thread() {
@Override
public void run() {
try {
thread1.join();//join方法會(huì)等待thread1運(yùn)行完畢,才繼續(xù)執(zhí)行下面的代碼。
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.yield();//暫時(shí)讓出cpu,執(zhí)行其他任務(wù)
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
initString();
}
};
thread2.start();
}
}
多線程知識(shí)點(diǎn)synchronized wait join yield
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 前言:在面試過程中 關(guān)于多線程編程這一塊是經(jīng)常問到的 為了更好的理解關(guān)于多線程編程基礎(chǔ)特地的記錄此文章把思路理清楚...
- wait、notify機(jī)制通常用于等待機(jī)制的實(shí)現(xiàn),調(diào)用wait進(jìn)入等待狀態(tài),需要的時(shí)候調(diào)用notify或notif...
- 文/雨涵 曾任性的點(diǎn)燃八月的熱潮,捧起花果梨香,品讀月光 曾將七月林中蟬鳴鳥唱放飛,彈起幽雅,深邃的小巷 曾把六月...
- 本文長(zhǎng)期更新,可以通過你自己的方法保存此文鏈接 好書很多,但是要選擇一本適合自己的,在精不在多 10+本新手入門資...