读写锁 ReadWriteLock 实例代码 package com.ansatsing.juc.readWriteLock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /* * 1. ReadWriteLock : 读写锁 * * 写写/读写 需要“互斥” * 读读 不需要互斥 * */ public class ReadWriteLockDemo { public static void main(String[] args) { final Stock rw = new Stock(); for (int i = 0; i < 100; i++) { if(i<10) { new Thread(new Runnable() { @Override public void run() { rw.set((int) (Math.random() * 101)); } }, "Write:"+i).start(); } new Thread(new Runnable() { @Override public void run() { rw.get(); } }).start(); } } } class Stock { private int index;// 股票指数 private ReadWriteLock lock = new ReentrantReadWriteLock(true); public void get() { lock.readLock().lock(); // 上锁 try { try { TimeUnit.MILLISECONDS.sleep(150); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 当前股票指数: " + index); } finally { lock.readLock().unlock(); // 释放锁 } } public void set(int index) { lock.writeLock().lock(); try { try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.index = index; System.out.println(Thread.currentThread().getName() + "设置股票指数为:" + index); } finally { lock.writeLock().unlock(); } } } 疑问 读数据的方法改成返回值,那代码该怎么实现? |
|