java 多线程(ReadWriteLock)

复制代码
package com.example;

public class App {

    public static void main(String[] args) {
        Info info = new Info();
        ReadInfo ri = new ReadInfo(info);
        WriteInfo wi = new WriteInfo(info);
        
        Thread t1 = new Thread(ri,"ri1");
        Thread t2 = new Thread(ri,"ri2");
        Thread t3 = new Thread(ri,"ri3");
        Thread t4 = new Thread(wi,"wi1");
        Thread t5 = new Thread(wi,"wi2");
        
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();    
    }
}
复制代码
复制代码
package com.example;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Info {
    private int num;
    //ReadWriteLock 可以理解为对synchronized更加精细化的管理
    private ReadWriteLock lock;
    
    public Info(){
        this.num = 0;
        lock = new ReentrantReadWriteLock();
    }
    
    public int getNum(){
        lock.writeLock().lock();
        int output = this.num;
        lock.writeLock().unlock();
        return output;
    }
    
    public void setNum(int input){
        lock.readLock().lock();
        this.num = input;
        lock.readLock().unlock();
    }    
}
复制代码
复制代码
package com.example;

public class ReadInfo implements Runnable {
    
    private Info info;
    
    public ReadInfo(Info in){
        this.info = in;
    }
    
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            System.out.println(Thread.currentThread().getName() + "   " + info.getNum());
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
复制代码
复制代码
package com.example;

public class WriteInfo implements Runnable {
    
    private Info info;
    
    public WriteInfo(Info in){
        this.info = in;
    }
    
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            info.setNum(i + info.getNum());
            System.out.println(Thread.currentThread().getName() + "  setInfo:  " + info.getNum());
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
复制代码

 

posted @   Fredric_2013  阅读(168)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示