1. 程式人生 > >一道面試題:通過wait和notify的兩個執行緒互動輸出thread1-1...thread1-5,thread2-6...thread2-10...

一道面試題:通過wait和notify的兩個執行緒互動輸出thread1-1...thread1-5,thread2-6...thread2-10...

這是一道關於多執行緒的面試題,好久沒有做過這種多執行緒的題了,手有點生,那麼就來敲一敲

package threadDemo;

/*
 * 多執行緒的交叉列印
 */
public class threaddemo1 {
    public static void main(String[] args) {
        num num = new num();
        Thread t1 = new Thread(new thread1(num));
        Thread t2 = new Thread(new thread1(num));
        t1.start();
        t2.start();
    }
}

class
num {
public int count; public num() { } } class thread1 implements Runnable { private final num num; public thread1(num num) { this.num = num; } @Override public void run() { synchronized (num) { while (num.count <= 20) { for
(int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "-" + num.count++); } num.notify(); try { num.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block
e.printStackTrace(); } } } } }