/** * @author: yanxuxin * @date: 2010-1-7 */ public class ReentrantReadWriteLockSample {
public static void main(String[] args) { testReadLock(); // testWriteLock(); }
public static void testReadLock() { final ReadWriteLockSampleSupport support = new ReadWriteLockSampleSupport(); support.initCache();
Runnable runnable = new Runnable() { public void run() { support.get("test"); } };
new Thread(runnable).start(); new Thread(runnable).start();
new Thread(new Runnable() { public void run() { support.put("test", "test"); } }).start(); }
public static void testWriteLock() { final ReadWriteLockSampleSupport support = new ReadWriteLockSampleSupport(); support.initCache();
new Thread(new Runnable() { public void run() { support.put("key1", "value1"); } }).start();
new Thread(new Runnable() { public void run() { support.put("key2", "value2"); } }).start();
new Thread(new Runnable() { public void run() { support.get("key1"); } }).start(); } }
class ReadWriteLockSampleSupport { private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock();