java多线程之等待换性机制简单使用

来源:互联网 发布:原生js 双向绑定 编辑:程序博客网 时间:2024/06/04 19:40

等待换新机制的简单使用
wait
notify ()

(1)都使用在同步中,因为要对持有监视器(锁)的线程操作所以要使用在同步中,因为只有同步才具有锁。
(2)为什么这些操作线程的方法要定义object类中呢?因为这些方法在操作同步中线程时。都必须要标识他们所操作线程只有的锁只有同一个锁上的被等待线程,可以被同一个锁上的notify唤醒。
(3)不可以对不同锁中的线程进行唤醒。而锁可以使任意对象,所以可以被任意对象调用的方法定义object类中。


public class WaitAndnotify{    public static void main(String[] args) {        Resource r = new Resource();        LineOneIns in = new LineOneIns(r);        LineTowOuts out = new LineTowOuts(r);        Thread tin = new Thread(in);        Thread tout = new Thread(out);        tin.start();        tout.start();    }}// 资源类class Resource {    public String name;    public String sex;    public boolean flags;    public void set(String names, String sexs) {        synchronized (ResourceS.class) {            if (flags) {                try {                    ResourceS.class.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            this.name = names;            this.sex = sexs;            flags = true;            System.out.println("写入的资源完毕释放执行权");            ResourceS.class.notify();        }    }    public void out() {        synchronized (ResourceS.class) {            if (!flags) {                try {                    ResourceS.class.wait();                } catch (InterruptedException e) {                    e.printStackTrace();                }            }            System.out.println("写入的资源是:"+name + ".........." + sex);            flags = false;            ResourceS.class.notify();        }    }}class LineOneIns implements Runnable {    Resource r;    LineOneIns(Resource r) {        this.r = r;    }    public void run() {        boolean flag = false;        while (true) {            if (flag) {                r.set("张杰", "男");                flag = false;            } else {                r.set("谢那", "女的");                flag = true;            }        }    }}class LineTowOuts implements Runnable {    Resource r;    LineTowOuts(Resource r) {        this.r = r;    }    public void run() {        while (true) {            r.out();        }    }}
原创粉丝点击