1114. 按序打印

https://leetcode-cn.com/problems/print-in-order/solution/an-xu-da-yin-by-leetcode/

三個主要問題:

競態(tài) 關(guān)鍵部分代碼獨占性(加鎖;通知阻塞線程)

死鎖

資源不足

個人喜好解法:https://leetcode-cn.com/problems/print-in-order/solution/li-yong-wait-he-notifyall-bao-zheng-shun-xu-qie-xi/

補充知識 AtomicInteger? http://www.itdecent.cn/p/bc7b6f14984e

java.util.concurrent.atomic 的包里有AtomicBoolean, AtomicInteger,AtomicLong,AtomicLongArray,

AtomicReference等原子類的類,主要用于在高并發(fā)環(huán)境下的高效程序處理,來幫助我們簡化同步處理.



參考https://blog.csdn.net/huaijiu123/article/details/86370668?修改

package leetCode1004;

class Foo {

int flag =1;

? ? int count =0;

? ? public int getCount() {

return count;

? ? }

public synchronized void printA(){

while(flag !=1){

try {

wait();

? ? ? ? ? ? }catch (InterruptedException e) {

e.printStackTrace();

? ? ? ? ? ? }

}

System.out.print(1);

? ? ? ? count++;

? ? ? ? flag =2;

? ? ? ? notifyAll();

? ? }

public synchronized void printB(){

while(flag !=2){

try {

wait();

? ? ? ? ? ? }catch (InterruptedException e) {

e.printStackTrace();

? ? ? ? ? ? }

}

System.out.print(2);

? ? ? ? count++;

? ? ? ? flag =3;

? ? ? ? notifyAll();

? ? }

public synchronized void printC(){

while(flag !=3){

try {

wait();

? ? ? ? ? ? }catch (InterruptedException e) {

e.printStackTrace();

? ? ? ? ? ? }

}

System.out.print(3);

? ? ? ? count++;

? ? ? ? flag =1;

? ? ? ? notifyAll();

? ? }

}

class MyThreadimplements Runnable{

private Fooprint;

? ? public MyThread(Foo print) {

this.print = print;

? ? }

@Override

? ? public void run() {

if(Thread.currentThread().getName().equals("A")){

print.printA();

? ? ? ? }else if(Thread.currentThread().getName().equals("B")){

print.printB();

? ? ? ? }else if(Thread.currentThread().getName().equals("C")){

print.printC();

? ? ? ? }

}

public static void main(String[] args) {

Foo print =new Foo();

? ? ? ? MyThread mt =new MyThread(print);

? ? ? ? Thread th1 =new Thread(mt,"A");

? ? ? ? Thread th2 =new Thread(mt,"B");

? ? ? ? Thread th3 =new Thread(mt,"C");

? ? ? ? th1.start();

? ? ? ? th2.start();

? ? ? ? th3.start();

? ? }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容