多线程-ReentrantReadWriteLock读写锁

public class ReadWriteLockTest {
    ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Lock readLock = readWriteLock.readLock();
    Lock writeLock = readWriteLock.writeLock();
    List userList = new ArrayList<>();

    public static void main(String[] args) {
        ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
        for(int i=0; i<100; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    readWriteLockTest.read();
                }
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    readWriteLockTest.write();
                }
            }).start();
        }
    }

    public void read(){
        readLock.lock();
        try {
            System.out.println(JSON.toJSONString(userList));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public void write(){
        writeLock.lock();
        Thread thread = Thread.currentThread();
        try {
            User user = new User()
                    .setId(thread.getPriority())
                    .setName(thread.getName())
                    .setBirthday(new Date());
            userList.add(user);
           // System.out.println(JSON.toJSONString(userList));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }
}

 

你可能感兴趣的:(java,多线程)