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();
}
}
多线程复习之lock锁
最新推荐文章于 2024-11-06 17:04:56 发布
该博客介绍了如何在Java中使用ReentrantLock进行线程同步,通过InputThread1和OutThread1类展示了如何实现数据的交替读写。在Res1类中定义了Lock和Condition,用于控制并发访问。输入线程在更新数据后唤醒等待的输出线程,而输出线程在读取数据后释放锁并等待新的数据准备就绪。
2626

被折叠的 条评论
为什么被折叠?



