java 5 ReadWriteLock
import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockTest { private static List<String> list = new ArrayList<String>(); public static void main(String[] args) { for(int i = 0; i < 10; i++) { list.add("init - " + i); } new Thread(new Runnable() { public void run() { try { ReadWriteLockTest.add(); } catch (Exception e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { public void run() { try { ReadWriteLockTest.get(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } private static ReadWriteLock lock = new ReentrantReadWriteLock(); private static void add() throws Exception { for(int i = 0; i < 10; i++) { lock.writeLock().lock(); list.add("add-" + i); lock.writeLock().unlock(); System.out.println("add " + i); Thread.sleep(500); } } private static void get() throws Exception { lock.readLock().lock(); for(String str : list) { System.out.println("get- " + str); Thread.sleep(500); } lock.readLock().unlock(); } }
上面有2个线程同时对list变量读写,如果不使用读写锁,则程序会抛出异常。
多个读锁不互斥,读锁也写锁互斥,写锁与写锁互斥。