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();
? ? }
}