- class Demo1_Notify {
-
- public static void main(String[] args) {
- final Printer p = new Printer();
-
- new Thread(){
- public void run() {
- while(true)
- try {
- p.print1();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
-
- new Thread(){
- public void run() {
- for(;;)
- try {
- p.print2();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
-
- new Thread(){
- public void run() {
- for(;;)
- try {
- p.print3();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
-
- }
- class Printer {
- private int flag = 1; // 创建一个标记变量, 代表目前应该执行哪个方法
- public synchronized void print1() throws Exception {
- while (flag != 1) // 执行之前判断, 如果刚刚执行过, 就等待
- wait();
- System.out.print("传");
- System.out.print("智");
- System.out.print("播");
- System.out.print("客");
- System.out.print("\r\n");
- flag = 2; // 1执行后轮到2了
- notifyAll(); // 执行之后通知另外一个线程
- }
-
- public synchronized void print2() throws Exception {
- while (flag != 2) // 执行之前判断, 如果刚刚执行过, 就等待
- wait();
- System.out.print("黑");
- System.out.print("马");
- System.out.print("程");
- System.out.print("序");
- System.out.print("员");
- System.out.print("\r\n");
- flag = 3; // 2结束后又应该回到1
- notifyAll(); // 执行之后通知另外一个线程
- }
-
- public synchronized void print3() throws Exception {
- while (flag != 3)
- wait();
- System.out.print("i");
- System.out.print("t");
- System.out.print("c");
- System.out.print("a");
- System.out.print("s");
- System.out.print("t");
- System.out.print("\r\n");
- flag = 1;
- notifyAll();
- }
-
- }
复制代码 答案见代码说明 |