- class Demo2_Exercise {
-
- public static void main(String[] args) {
- final Printer p = new Printer();
-
- new Thread(){
- public void run() {
- for (int i = 1; i <= 3; i++)
- try {
- p.print1();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
-
- new Thread(){
- public void run() {
- for (int i = 1; i <= 3; i++)
- try {
- p.print2();
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
-
- }
- class Printer {
- private int flag = 1;
-
- public synchronized void print1() throws Exception {
- if (flag != 1)
- wait();
- for (int i = 1; i <= 3; i++)
- System.out.println("线程1: " + i);
- System.out.println();
- flag = 2;
- notify();
- }
-
- public synchronized void print2() throws Exception {
- if (flag != 2)
- wait();
- for (int i = 1; i <= 3; i++)
- System.out.println("线程2: " + i);
- System.out.println();
- flag = 1;
- notify();
- }
- }
复制代码 线程等待, 就调用wait()
notify()方法是随机唤醒一个线程 |