三、并发编程之多线程间通讯

1、wait、notify方法

1.1、wait、notify必须在synchronized中进行使用

public class Res {
    public String userSex;
    public String userName;
    public boolean flag = false;
}
public class InThread extends Thread {
    private Res res;

    public InThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
            synchronized (res) {
                if (res.flag) {
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0) {
                    res.userName = "张三";
                    res.userSex = "男";
                } else {
                    res.userName = "小红";
                    res.userSex = "女";
                }
                count = (count + 1) % 2;
                res.flag = true;
                res.notify();
            }
        }
    }
}
public class OutThread extends Thread {
    private Res res;

    public OutThread (Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (res) {
                if (!res.flag) {
                    try {
                        res.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(res.userName + " -- " + res.userSex);
                res.flag = false;
                res.notify();
            }
        }
    }
}
public class ThreadApp {
    public static void main(String[] args) {
        Res res = new Res();
        InThread in = new InThread(res);
        OutThread out = new OutThread(res);
        in.start();
        out.start();
    }
}

2、wait、sleep的区别

2.1、sleep属于Thread的方法,wait属于Object的方法

2.2、sleep方法导致程序暂停执行时间,让出cpu给其他线程,但是他的监控状态依然保持着,当指定时间到了又会自动恢复运行状态。

2.3、在调用sleep方法时,线程不会释放对象锁。而当调用wait方法时,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对次对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。

3、lock锁

lock锁与synchronized关键字类似的同步功能,但需要在使用时手动获取锁和释放锁。

Lock lock = new ReentrantLook();

lock.lock();

try{

 // 可能会出现线程安全的操作

} finally {

//  一定在finally中释放锁

lock.unlock();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值