Communication between java threads

Keywords: Java

Wait for wake-up mechanism:

wait(),notify(),notifyAll() are all used in synchronization, because the thread holding the monitor (lock) is to be operated.

So use it in synchronization, because only synchronization has a lock.

The reason why these methods are defined in the Object class is that they must identify the lock held by the thread they operate. Only the waiting thread on the same lock can be awakened by the notify on the same lock. The waiting and waking threads in different locks can be awakened. The waiting and waking must be the same lock.

The lock can be any Object, so the method that can be called by any Object is defined in the Object.

class Res {
    private String name;
    private String sex;
    private boolean flag;

    public synchronized void set(String name, String sex) {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.name = name;
        this.sex = sex;
        this.flag = true;
        this.notify();
    }

    public synchronized void print() {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(name + "......" + sex);
        this.flag = false;
        this.notify();
    }
}

class Input implements Runnable {
    private Res r;

    public Input(Res r) {
        this.r = r;
    }

    @Override
    public void run() {
        int x = 0;
        while (true) {
            if (x == 0) {
                r.set("mike", "man");
            } else {
                r.set("Lily", "female");
            }
            x = (x + 1) % 2;
        }
    }
}

class Output implements Runnable {
    private Res r;

    public Output(Res r) {
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
            r.print();
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        Res r = new Res();
        new Thread(new Input(r)).start();
        new Thread(new Output(r)).start();
    }
}

Posted by freakyG on Tue, 31 Mar 2020 13:08:48 -0700