博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

wait and notifyAll

Posted on 2013-01-29 14:30  钟悍  阅读(243)  评论(0编辑  收藏  举报
package com.karl.multithread;

public class Test {
    public static void main(String[] args) {
        Printer p = new Printer();
        Thread t1 = new NumberPrinter(p);
        Thread t2 = new LetterPrinter(p);
        t1.start();
        t2.start();
    }
}

class Printer {
    private int index = 1;
    public synchronized void print(int i) {
        while (index % 3 == 0) {
            try {
                wait();
            } catch (Exception e) {
            }
        }
        System.out.print(" " + i);
        index++;
        notifyAll();
    }

    public synchronized void print(char c) {
        while (index % 3 != 0) {
            try {
                wait();
            } catch (Exception e) {
            }
        }
        System.out.print(" " + c);
        index++;
        notifyAll();
    }
}

class NumberPrinter extends Thread {
    private Printer p;
    public NumberPrinter(Printer p) {
        this.p = p;
    }
    public void run() {
        for (int i = 1; i <= 52; i++) {
            p.print(i);
        }
    }
}

class LetterPrinter extends Thread {
    private Printer p;
    public LetterPrinter(Printer p) {
        this.p = p;
    }
    public void run() {
        for (char c = 'A'; c <= 'Z'; c++) {
            p.print(c);
        }
    }
}

 1 2 A 3 4 B 5 6 C 7 8 D 9 10 E 11 12 F 13 14 G 15 16 H 17 18 I 19 20 J 21 22 K 23 24 L 25 26 M 27 28 N 29 30 O 31 32 P