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

等待换新机制的简单使用
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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值