读写锁样例

package thread.lock;
public class Test {

    public static void main(String[] args) {
        final Printer printer = new Printer();

        Thread thread1 = new Thread(){
            @Override
            public void run() {
                printer.read("thread1 read...");
                printer.write("thread1 write...");
            }
        };
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                printer.read("thread2 read...");
                printer.write("thread2 write...");
            }
        };
        thread1.start();
        thread2.start();
    }
}
package thread.lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Printer {
    ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 读操作
     * @author JIANGBIN
     * @param str
     */
    public void read(String str){
        lock.readLock().lock();//读锁1
        try{
            for (int i = 0; i < 3; i++) {
                try {
                    System.out.println(str);
                    Thread.sleep(200);//暂停100ms,不释放锁,以便更好的观察输出结果
                } catch (InterruptedException e) {

                }
            }
        }finally{
            lock.readLock().unlock();//解锁,要放在finnall块里面
        }
    }

    /**
     * 写操作
     * @author JIANGBIN
     * @param str
     */
    public void write(String str){
        lock.writeLock().lock();//写锁
        try{for (int i = 0; i < 3; i++) {
            try {
                System.out.println(str);
                Thread.sleep(100);//暂停100ms,不释放锁,以便更好的观察输出结果
            } catch (InterruptedException e) {

            }
        }
        }finally{
            lock.writeLock().unlock();//解锁
        }
    }
}

输出结果:

thread1 read...
thread2 read...
thread2 read...
thread1 read...
thread2 read...
thread1 read...
thread2 write...
thread2 write...
thread2 write...
thread1 write...
thread1 write...
thread1 write...

总结:读锁之间可以变法访问,读锁和写锁直接互斥,写锁和写锁之间互斥

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值