当前位置:首页 > 开发 > 编程语言 > Java > 正文

Java 读写锁demo

发表于: 2014-09-11   作者:annan211   来源:转载   浏览:
摘要: java 读写锁 原理 和 实例 package thread; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReenRead
java 读写锁 原理 和 实例
package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReenReadWriteLockDemo {

	public static void main(String[] args) {
		Data data = new Data();
		for(int i=0;i<3;i++){
			new Thread(new Reader(data)).start();

			new Thread(new Writer(data)).start();
		}
	}

}

class Data{
	private static final int length = 10;
	private  List<Integer> dataList = new ArrayList<Integer>(length);

	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

	public void get(Data data){
		lock.readLock().lock();
		try {
			if(data.dataList.size()>0){
				System.out.println(Thread.currentThread().getName()+"--获取数据----"+data.dataList.remove(0));
			}
		}finally{
			lock.readLock().unlock();
		}
	}
	public void set(Data data){
		lock.writeLock().lock();
			try {
				if(data.dataList.size()<data.length){
				int num = new Random().nextInt(10000);
				dataList.add(num);
				System.out.println(Thread.currentThread().getName()+"--写入数据-------"+num);
				}
			}finally{
				lock.writeLock().unlock();
			}
	}
}

class Reader implements Runnable{
	private Data data;
	public Reader(Data data){
		this.data = data;
	}
	@Override
	public void run() {
		while(true)
		data.get(data);
	}
}

class Writer implements Runnable {
	private Data data;
	public Writer(Data data){
		this.data = data;
	}
	@Override
	public void run() {
		while(true)
		data.set(data);
	}
}





Java 读写锁demo

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号