java常见面试题3:线程间通信

写两个线程,一个线程打印 1~52,另一个线程打印字母A-Z

打印顺序为12A34B56C78D……5152Z。要求用线程间的通信。

 

代码清单:

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 NOPrinter implements Runnable {
    private Printer p;

    NOPrinter(Printer p) {
        this.p = p;
    }

    public void run() {
        for (int i = 1; i <= 52; i++) {
            p.print(i);
        }
    }
}

class LetterPrinter implements Runnable {
    private Printer p;

    LetterPrinter(Printer p) {
        this.p = p;
    }

    public void run() {
        for (char c = 'A'; c <= 'Z'; c++) {
            p.print(c);
        }
    }
}

public class ResourceDemo {
    public static void main(String[] args) {
        Printer p = new Printer();
        NOPrinter np = new NOPrinter(p);
        LetterPrinter lp = new LetterPrinter(p);

        Thread th1 = new Thread(np);
        Thread th2 = new Thread(lp);
        th1.start();
        th2.start();
    }
}

 

posted on 2013-11-23 14:23  On_Way  阅读(601)  评论(0编辑  收藏  举报