思路:java.util.concurrent.locks包下面ReadWriteLock接口,该接口下面的实现类ReentrantReadWriteLock维护了两个锁读锁和解锁,可用该类实现这个功能,很简单
import java.util.Date; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 你需要实现一个高效的缓存,它允许多个用户读,但只允许一个用户写,以此来保持它的完整性,你会怎样去实现它? * @author user * */ public class Test2 { public static void main(String[] args) { for (int i = 0; i < 3; i++) { new Thread(new Runnable() { @Override public void run() { MyData.read(); } }).start(); } for (int i = 0; i < 3; i++) { new Thread(new Runnable() { @Override public void run() { MyData.write("a"); } }).start(); } } } class MyData{ //数据 private static String data = "0"; //读写锁 private static ReadWriteLock rw = new ReentrantReadWriteLock(); //读数据 public static void read(){ rw.readLock().lock(); System.out.println(Thread.currentThread()+"读取一次数据:"+data+"时间:"+new Date()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { rw.readLock().unlock(); } } //写数据 public static void write(String data){ rw.writeLock().lock(); System.out.println(Thread.currentThread()+"对数据进行修改一次:"+data+"时间:"+new Date()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { rw.writeLock().unlock(); } } }
运行结果如下:
Thread[Thread-5,5,main]对数据进行修改一次:a时间:Sun Sep 10 20:52:07 CST 2017 Thread[Thread-4,5,main]对数据进行修改一次:a时间:Sun Sep 10 20:52:08 CST 2017 Thread[Thread-3,5,main]对数据进行修改一次:a时间:Sun Sep 10 20:52:09 CST 2017 Thread[Thread-2,5,main]读取一次数据:0时间:Sun Sep 10 20:52:10 CST 2017 Thread[Thread-0,5,main]读取一次数据:0时间:Sun Sep 10 20:52:10 CST 2017 Thread[Thread-1,5,main]读取一次数据:0时间:Sun Sep 10 20:52:10 CST 2017
分析结果可知:读取的时候都是同一个时间,而修改数据是不同时间的
时间: 2024-10-24 18:55:29