码迷,mamicode.com
首页 > 编程语言 > 详细

java 5 ReadWriteLock

时间:2014-10-26 22:52:09      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   使用   java   for   sp   

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

标签:style   blog   color   io   ar   使用   java   for   sp   

原文地址:http://www.cnblogs.com/java-koma/p/4052889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!