多线程学习3(多线程之间实现通讯)

多线程学习3(多线程之间实现通讯)

什么是多线程之间通讯?

多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同。
画图演示

多线程之间通讯需求

需求:第一个线程写入(input)用户,另一个线程取读取(out)用户.实现读一个,写一个操作。
在这里插入图片描述
代码实现:

//共享资源
class User{
    public String name;
    public String sex;
}

//输入线程
class Out extends Thread{
    User user;
    public Out(User user){
        this.user = user;
    }

    @Override
    public void run(){
        int count = 0;
        while (true){
            if (count == 0){
                user.name = "苍老师";
                user.sex = "女";
            }else{
                user.name = "白老师";
                user.sex = "男";
            }
            count = (count + 1) % 2;
        }
    }
}

//输出线程
class Input extends Thread{
    User user;
    public Input(User user){
        this.user = user;
    }

    @Override
    public void run(){
        while (true){
            System.out.println(user.name+","+user.sex);
        }
    }
}

public class OutInputThread {

    public static void main(String[] args){
        User user = new User();
        Out out = new Out(user);
        Input input = new Input(user);
        out.start();
        input.start();
    }
}

结果如下:
在这里插入图片描述
注意:数据发生错乱,造成线程安全问题

解决线程安全问题

输入输出线程上加上synchronized

class User{
    public String name;
    public String sex;
}

class Out extends Thread{

    User user;

    public Out(User user){
        this.user = user;
    }

    @Override
    public void run(){
        int count = 0;
        while (true){
            synchronized (user){
                if (count == 0){
                    user.name = "苍老师";
                    user.sex = "女";
                }else{
                    user.name = "白老师";
                    user.sex = "男";
                }
                count = (count + 1) % 2;
            }
        }
    }
}

class Input extends Thread{

    User user;

    public Input(User user){
        this.user = user;
    }

    @Override
    public void run(){
        while (true){
            synchronized (user){
                System.out.println(user.name+","+user.sex);
            }
        }
    }
}

public class OutInputThread {

    public static void main(String[] args){
        User user = new User();
        Out out = new Out(user);
        Input input = new Input(user);
        out.start();
        input.start();
    }
}

结果如下:
在这里插入图片描述

wait()、notify、notifyAll()方法

wait()、notify()、notifyAll()是三个定义在Object类里的方法,可以用来控制线程的状态。
这三个方法最终调用的都是jvm级的native方法。随着jvm运行平台的不同可能有些许差异。
如果对象调用了wait方法就会使持有该对象的线程把该对象的控制权交出去,然后处于等待状态。
如果对象调用了notify方法就会通知某个正在等待这个对象的控制权的线程可以继续运行。
如果对象调用了notifyAll方法就会通知所有等待这个对象控制权的线程继续运行。
注意:一定要在线程同步中使用,并且是同一个锁的资源

class User{
    public String name;
    public String sex;
    //线程通讯标识
    public boolean flag = false;
}

class Out extends Thread{

    User user;

    public Out(User user){
        this.user = user;
    }

    @Override
    public void run(){
        int count = 0;
        while (true){
            synchronized (user){
                //为false时生产者生产,消费者等待,为true时生产者等待,消费者开始消费
                if(user.flag){
                    try {
                        user.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0){
                    user.name = "苍老师";
                    user.sex = "女";
                }else{
                    user.name = "白老师";
                    user.sex = "男";
                }
                count = (count + 1) % 2;
                //当生产者生产完时就开始等待消费者消费
                user.flag = true;
                //唤醒等待拿user对象的线程
                user.notify();
            }
        }
    }
}

class Input extends Thread{

    User user;

    public Input(User user){
        this.user = user;
    }

    @Override
    public void run(){
        while (true){
            synchronized (user){
                //为true时消费者开始消费,生产者开始等待,false时消费者开始等待,生产者开始生产
                if(!user.flag){
                    try {
                        user.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(user.name+","+user.sex);
                user.flag = false;
                //唤醒等待拿user对象的线程
                user.notify();
            }
        }
    }
}

public class OutInputThread {

    public static void main(String[] args){
        User user = new User();
        Out out = new Out(user);
        Input input = new Input(user);
        out.start();
        input.start();
    }
}

结果如下:
在这里插入图片描述

wait与sleep区别?

对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。
sleep()方法导致了程序暂停执行指定的时间,让出cpu该其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。
在调用sleep()方法的过程中,线程不会释放对象锁。
而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备
获取对象锁进入运行状态。

JDK1.5-Lock

在 jdk1.5 之后,并发包中新增了 Lock 接口(以及相关实现类)用来实现锁功能,Lock 接口提供了与 synchronized 关键字类似的同步功能,但需要在使用时手动获取锁和释放锁

Lock写法

Lock lock  = new ReentrantLock();
lock.lock();
try{
	//可能会出现线程安全的操作
}finally{
	//一定在finally中释放锁
	//也不能把获取锁在try中进行,因为有可能在获取锁的时候抛出异常
  lock.ublock();
}

Lock 接口与 synchronized 关键字的区别

Lock 接口可以尝试非阻塞地获取锁 当前线程尝试获取锁。如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁。
Lock 接口能被中断地获取锁 与 synchronized 不同,获取到锁的线程能够响应中断,当获取到的锁的线程被中断时,中断异常将会被抛出,同时锁会被释放。
Lock 接口在指定的截止时间之前获取锁,如果截止时间到了依旧无法获取锁,则返回。

Condition用法

Condition的功能类似于在传统的线程技术中的,Object.wait()和Object.notify()的功能。

class UserInfo{
    public String name;
    public String sex;
    //线程通讯标识
    public boolean flag = false;

    //定义lock锁
    Lock lock = new ReentrantLock();
}

class Outa extends Thread{
    private UserInfo user;
    Condition condition;
    public Outa(UserInfo user,Condition condition){
        this.user = user;
        this.condition = condition;
    }

    @Override
    public void run(){
        int count = 0;
        while (true){
            try {
                //开始上锁
                user.lock.lock();
                if(user.flag){
                    try {
                        //线程等待等同于user.wait();
                        condition.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (count == 0){
                    user.name = "苍老师";
                    user.sex = "女";
                }else{
                    user.name = "白老师";
                    user.sex = "男";
                }
                count = (count + 1) % 2;
                user.flag = true;
                //唤醒线程 等同于 notify()
                condition.signal();
            }catch (Exception e){

            }finally {
                user.lock.unlock();
            }

        }
    }
}

class Inputa extends Thread{

    private UserInfo user;
    Condition condition;
    public Inputa(UserInfo user,Condition condition){
        this.user = user;
        this.condition = condition;
    }

    @Override
    public void run(){
        while (true){
            try {
                //开始上锁
                user.lock.lock();
                //为true时消费者开始消费,生产者开始等待,false时消费者开始等待,生产者开始生产
                if(!user.flag){
                    try {
                        //线程等待等同于user.wait();
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(user.name+","+user.sex);
                user.flag = false;
                //唤醒线程 等同于 notify()
                condition.signal();
            }catch (Exception e){

            }finally {
                //释放锁
                user.lock.unlock();
            }
        }
    }
}
public class ThreadLock {
    public static void main(String[] args){
        UserInfo user = new UserInfo();
        Condition condition = user.lock.newCondition();
        Outa out = new Outa(user,condition);
        Inputa input = new Inputa(user,condition);
        out.start();
        input.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值