記得最後一題是有關多線程調度的,做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