Java multi-thread communication of wait () and notify () method

1.wait () method and a sleep () method:

wait () method to release the lock in waiting; sleep () does not release the lock While waiting, holding the lock sleep.

2.notify():

Random wake up a thread, the thread will wait in the queue waiting for a synchronization queue moved from the waiting queue.

public class Demo_Print {
    public static void main(String[] args) {
        Print p = new Print();
        new Thread() {
            public void run() {
                while (true) {
                    p.print1();
                }
            };
        }.start();

        new Thread() {
            public void run() {
                while (true) {
                    p.print2();
                }
            };
        }.start();
    }
}

class Print {
    int flag = 1;

    public synchronized void print1() {
        if (flag != 1) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.print("你");
        System.out.print("好");
        System.out.print("吗????????????");
        System.out.println();

        flag = 2;
        this.notify();
    }

    public synchronized void print2() {
        if (flag != 2) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        System.out.print("我");
        System.out.print("好");
        System.out.println();

        flag = 1;
        this.notify();
    }
}

In this case, the realization of a question-and-answer thread synchronous communication. When turned on after the process wait () method, to wake a thread by changing the flag value, further another method of implementation.

Guess you like

Origin www.cnblogs.com/springa/p/12631483.html