首页 > 代码库 > java 5 ReadWriteLock
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变量读写,如果不使用读写锁,则程序会抛出异常。
多个读锁不互斥,读锁也写锁互斥,写锁与写锁互斥。
java 5 ReadWriteLock
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。