多线程复习之lock锁

该博客介绍了如何在Java中使用ReentrantLock进行线程同步,通过InputThread1和OutThread1类展示了如何实现数据的交替读写。在Res1类中定义了Lock和Condition,用于控制并发访问。输入线程在更新数据后唤醒等待的输出线程,而输出线程在读取数据后释放锁并等待新的数据准备就绪。
package com.lyon.demo.test.mayi;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁
 */

class Res1{
    public String name;
    public String sex;
    public Lock lock = new ReentrantLock();
    public boolean flag;
    Condition condition = lock.newCondition();
}

class InputThread1 extends Thread{

    public Res1 res;
    public InputThread1(Res1 res){
        this.res = res;
    }

    @Override
    public void run() {
        int count = 0;
        while (true) {
                res.lock.lock();
                try{
                    if (res.flag) {
                        try {
                            //等待
                            res.condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (count==0) {
                        res.name = "lyon";
                        res.sex = "男";
                    }else{
                        res.name = "小红";
                        res.sex = "女";
                    }
                    count=(count+1)%2;
                    res.flag = true;
                    res.condition.signal();

                }catch (Exception e){

                }finally {
                    //释放锁
                    res.lock.unlock();
                }
        }
    }
}

class OutThread1 extends Thread{

    public Res1 res;
    public OutThread1(Res1 res){
        this.res = res;
    }

    @Override
    public void run() {
        //不要将同步锁放在while上面,或者是方法上面,这样会导致一直写,或者一直读
        while (true) {
            try{
                res.lock.lock();
                if (!res.flag) {
                    res.condition.await();
                }

                System.out.println(res.name+"---"+res.sex);
                res.flag = false;
                res.condition.signal();
            }catch (Exception e){

            }finally {
                //
                res.lock.unlock();
            }
        }
    }
}

public class Demo6 {
    public static void main(String[] args) {
        Res1 res = new Res1();
        InputThread1 inputThread = new InputThread1(res);
        OutThread1 outThread = new OutThread1(res);
        inputThread.start();
        outThread.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值