關於阿里春招的一道多執行緒面試題的個人愚見
阿新 • • 發佈:2019-01-09
原題如下:
多執行緒,5個執行緒內部列印hello和word,hello在前,要求提供一種方法使得5個執行緒先全部打印出hello後再列印5個word。
參考文章:
程式碼如下:
five.java
public class Five { //定義一個公共鎖物件 private static CommonLock lock; public static void main(String[] args) { //初始化該物件,1為條件,為鎖初始化status的值,使全部子執行緒在開始之初僅有thread1能繼續執行, //而其他執行緒進入阻塞狀態,待thread1列印完hello後,將nextStatus賦值給currentStatue, //並通過公共鎖lock喚醒所有以lock物件為鎖的子執行緒 lock =new CommonLock(1); Thread thread1 = new Thread(new MyRunnable(lock,1,2),"執行緒1"); Thread thread2 = new Thread(new MyRunnable(lock,2,3),"執行緒2"); Thread thread3 = new Thread(new MyRunnable(lock,3,4),"執行緒3"); Thread thread4 = new Thread(new MyRunnable(lock,4,5),"執行緒4"); Thread thread5 = new Thread(new MyRunnable(lock,5,1),"執行緒5"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); } }
MyRunnable.java
public class MyRunnable implements Runnable { //公共鎖物件 private CommonLock lock; //執行緒標誌,建立執行緒時初始化該值,並在run()方法中判斷lock物件的status變數是否與其相等,是則執行 private int currentStatuc; //若該子執行緒得以執行並列印完後,將lock物件的status設定為該值,之後喚醒所有使用該鎖的子執行緒 private int nextStatus; public MyRunnable(CommonLock lock, int currentStatuc, int nextStatus) { this.lock = lock; //初始化執行緒的標誌 this.currentStatuc = currentStatuc; //初始化下一個要執行的執行緒的標誌 this.nextStatus = nextStatus; } @Override public void run() { for(int j=0;j<2;j++){ synchronized (lock){ while(lock.getStatus()!=currentStatuc){ try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } lock.setStatus(nextStatus); if(j == 0){ System.out.print(Thread.currentThread().getName()+" Hello"); }else if(j == 1){ System.out.print(Thread.currentThread().getName()+" World"); } lock.notifyAll(); System.out.println(" lock.getStatus "+lock.getStatus()); } } } }
CommonLock.java
public class CommonLock {
//決定哪個子執行緒執行的條件
private int status;
public CommonLock(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
執行結果如下:
執行緒1 Hello lock.getStatus 2執行緒2 Hello lock.getStatus 3
執行緒3 Hello lock.getStatus 4
執行緒4 Hello lock.getStatus 5
執行緒5 Hello lock.getStatus 1
執行緒1 World lock.getStatus 2
執行緒2 World lock.getStatus 3
執行緒3 World lock.getStatus 4
執行緒4 World lock.getStatus 5
執行緒5 World lock.getStatus 1
以上僅為本人個人愚見,如有問題可在下方評論指出