美文网首页多线程
线程安全4 - Lock锁

线程安全4 - Lock锁

作者: 小超_8b2f | 来源:发表于2019-09-29 11:06 被阅读0次

0. Lock就是来替换synchronized的

public class TestSynchronized {
    
    public static void main(String[] args) {
        TestSynchronized obj = new TestSynchronized();
        obj.init();
    }
    
    private void init() {
        OutPut out = new OutPut();
        new Thread() {
            @Override
            public void run() {
                while(true)
                    out.print("hello world");
            };
        }.start();
        
        new Thread() {
            @Override
            public void run() {
                while(true)
                    out.print("guchunchaoxixihaha");
            };
        }.start();
    }
    
    
    class OutPut {
        public synchronized void print(String str) {
            for(int i = 0; i < str.length(); i++) {
                System.out.print(str.charAt(i));
            }
            System.out.println();
        }
    }
}

用Lock替代写法:

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

public class TestLock {

    public static void main(String[] args) {
        TestLock obj = new TestLock();
        obj.init();
    }
    
    private void init() {
        OutPut out = new OutPut();
        new Thread() {
            @Override
            public void run() {
                while(true)
                    out.print("hello world");
            };
        }.start();
        
        new Thread() {
            @Override
            public void run() {
                while(true)
                    out.print("guchunchaoxixihaha");
            };
        }.start();
    }
    
    
    class OutPut {
        Lock lock = new ReentrantLock();
        public void print(String str) {
            lock.lock();
            try {
                for(int i = 0; i < str.length(); i++) {
                    System.out.print(str.charAt(i));
                }
                System.out.println();
            } finally {
                lock.unlock();
            }
        }
    }
}

1. 读写锁:ReentrantReadWriteLock

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

public class ReadWriteLogTest {
    public static void main(String[] args) {
        final Queue3 queue = new Queue3();
        for(int i = 0; i < 3; i++) {
            new Thread(new Runnable() {  //读线程
                public void run() {
                    while(true) {
                        queue.get();
                    }
                }
            }).start();
             
            new Thread(new Runnable() { //写线程
                public void run() {
                    while(true) {
                        queue.write((int)(Math.random() * 1000));
                    }
                }
            }).start();
        }
        
    }
}


class Queue3 {
    
    //共享数据,只能有一个线程能写该数据,但可以有多个线程同时读取该数据
    private Object data = null;
    
    ReadWriteLock rwl = new ReentrantReadWriteLock();
    
    //读数据上读锁,多个读进程可同时进行,但不能喝写进程同时进行
    public void get() { 
        rwl.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " be ready to read data.");
            Thread.sleep((long)Math.random()*1000);
            System.out.println(Thread.currentThread().getName() + " have read data:" + data);
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwl.readLock().unlock();
        }
    }
    
    
    public void write(Object data) { //写数据上写锁,排他
        rwl.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + " be ready to write data.");
            Thread.sleep((long)Math.random()*1000);
            this.data = data; 
            System.out.println(Thread.currentThread().getName() + " have write data:" + data);
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rwl.writeLock().unlock();
        }
    }
}

2. Hibernate load()和get区别,用缓存实现代理类

User user = session.load(id,User.class); //无值则一个返回代理对象:User$Proxy
User user = session.get(id,User.class); //无值则返回null

User$Proxy extends User {
    private Integer id = id;
    
    User realUser = null;
    String getName() {
      if(realUser == null) {
        realUser = session.get(id);
        if(realUser == null) throw exception......
       return realUser.getName();
      }

    }
}

3. JAVA API ReentrantReadWriteLock 示例程序:读写锁共存

class CachedData {
   Object data;
   volatile boolean cacheValid;
   final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

   void processCachedData() {
     rwl.readLock().lock();
     if (!cacheValid) { //未被缓存过,初次赋值。上写锁,只能有一个线程写
       // Must release read lock before acquiring write lock
       rwl.readLock().unlock();
       rwl.writeLock().lock();
       try {
         // Recheck state because another thread might have
         // acquired write lock and changed state before we did.
         if (!cacheValid) {
           data = ...
           cacheValid = true;
         }
         // Downgrade by acquiring read lock before releasing write lock
         rwl.readLock().lock();
       } finally {
         rwl.writeLock().unlock(); // Unlock write, still hold read
       }
     }

     try {
       use(data); //读锁可以让多个线程同时读
     } finally {
       rwl.readLock().unlock();
     }
   }
 }

相关文章

  • 线程安全4 - Lock锁

    0. Lock就是来替换synchronized的 用Lock替代写法: 1. 读写锁:ReentrantRead...

  • 隐式锁与显示锁

    synchrouized 隐式锁 lock 显式锁 线程不安全,多个线程同时运行时,很可能发生线程安全问题 syn...

  • GIL线程全局锁

    线程全局锁(Global Interpreter Lock),即Python为了保证线程安全而采取的独立线程运行的...

  • Lock锁

    解决线程安全问题的方式三:Lock锁 --- JDK5.0新增的解决线程安全问题 一.示例代码class Win...

  • C++11多线程互斥锁`mutex`,`unique_lock`

    C++11多线程互斥锁mutex,unique_lock,lock_guard 互斥锁   互斥锁是线程中常用的线...

  • 多线程的锁相关内容

    重入锁 1.重入锁基本操作: 如果一个线程在lock.lock()到lock.unlock()之间,其他线程如果也...

  • Android(Java)枚举单例

    常规方式 懒汉式 DCL「双重检测锁:Double Checked Lock」 优点:线程安全;延迟加载;效率较高...

  • Reentreantlock里lock和trylock的区别

    举一个例子如下: 假如线程A和线程B使用同一个锁LOCK,此时线程A首先获取到锁LOCK.lock(),并且始终持...

  • 使用乐观锁优化并行操作

    Synchronized 和 Lock 实现的同步锁机制,这两种同步锁都属于悲观锁,是保护线程安全最直观的方式。悲...

  • 创建型模式 --- 单例

    1.懒汉式,线程不安全 2.懒汉式,线程安全 3.饿汉式,线程安全 4.枚举,线程安全 5.双检锁/双重校验锁

网友评论

    本文标题:线程安全4 - Lock锁

    本文链接:https://www.haomeiwen.com/subject/todoectx.html