面試時遭遇多線程

最近正忙於找工作,前天參加了迅雷的筆試,裏面考到的很多東西都忘記了,慚愧啊~~~
記得最後一題是有關多線程調度的,做web應用做久了,多線程也僅限於簡單的輪詢,而沒有做過什麼調度的事,結果當然是做不出來了。 回來後痛定思痛,找了多線程方面的書研究了一下,發現其實也不是太難。有個同事說過,要在面試中成長。亡羊補牢,這也算是一種進步吧,雖然有點後知後覺。
記得題目是這樣的:創建三個線程分別爲A,B,C, 要求打印輸入如下結果:ABCABCABC
我現在寫了個簡單的例子,實現了這個要求:
代碼爲:

class PrintMsg implements Runnable {
//開始打印
public synchronized void startPrint() {
notify();
}

@Override
public synchronized void run() {
for (int i = 0; i < 10; i++) {
try {
wait();
System.out.print(Thread.currentThread().getName());
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ThreadDemo {
public static void main(String[] args) throws Exception {
PrintMsg printMsg = new PrintMsg();
Thread threadA = new Thread(printMsg, "A");
Thread threadB = new Thread(printMsg, "B");
Thread threadC = new Thread(printMsg, "C");

threadA.start();
Thread.sleep(100);//休眠,保證thread進入wait堆棧的順序

threadB.start();
Thread.sleep(100);

threadC.start();
Thread.sleep(100);

printMsg.startPrint();
}
}

代碼運行結果爲:

ABCABCABCABCABCABCABCABCABCABC
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章