JAVA线程锁-读写锁

我只是一个虾纸丫 提交于 2020-03-20 00:11:07

 

  JAVA线程锁,除Lock的传统锁,又有两种特殊锁,叫读写锁ReadWriteLock

  其中多个读锁不互斥,读锁和写锁互斥,写锁和写锁互斥

例子:

/**
 * java线程锁分为读写锁 ReadWriteLock 其中多个读锁不互斥,读锁和写锁互斥,写锁和写锁互斥
 * 
 * @author
 * 
 * 
 *
 */
public class ReadWriteLockTest {

    public static void main(String[] args) {
        final Operation operation = new Operation();
        for (int i = 1; i <= 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    operation.getData();
                }
            }).start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    operation.putData(new Random().nextInt(1000));
                }
            }).start();
        }
    }

}
class Operation{
    private ReadWriteLock rwl = new ReentrantReadWriteLock();    //读写锁
    private int data;
    public void getData(){
        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" be readly get data ");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+" have data value :" + data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            rwl.readLock().unlock();
        }
    }
    public void putData(int data){
        rwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" be readly write data");
            Thread.sleep(1000);
            this.data = data;
            System.out.println(Thread.currentThread().getName() + " have write data value : "+ data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally{
            rwl.writeLock().unlock();
        }
    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!