多線程控制類-ReentrantReadWriteLock讀寫鎖演示

1.demo代碼:
package cn.yb.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 多線程控制類-讀寫鎖演示
 * 
 * @author yb
 *
 */
public class ReadWriteLockDemo {
	private Map<String, String> map = new HashMap<String, String>();// 操作map對象
	private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
	private ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();// 讀操作鎖
	private ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();// 寫操作鎖

	public String get(String key) {
		readLock.lock();// 讀操作鎖
		String name = Thread.currentThread().getName();
		try {
			System.out.println(name+"讀操作已加鎖,開始讀操作");
			Thread.sleep(3000);
			return map.get(key);
		} catch (Exception e) {
			e.printStackTrace();
			return key;
		} finally {
			readLock.unlock();
			System.out.println(name+"讀操作已解鎖,讀操作已經結束");
		}
	}
    public void put(String key,String value) {
    	writeLock.lock();
		String name = Thread.currentThread().getName();
		try {
			System.out.println(name+"寫操作已加鎖,開始寫操作");
			Thread.sleep(3000);
			map.put(key, value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			writeLock.unlock();
			System.out.println(name+"寫操作已解鎖,寫操作已經結束");
		}
    }
    public static void main(String[] args) {
		final ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
		readWriteLockDemo.put("key1", "value1");
		new Thread("讀線程1") {
			public void run() {
				System.out.println(readWriteLockDemo.get("key1"));				
			}
		}.start();
		new Thread("讀線程2") {
			public void run() {
				System.out.println(readWriteLockDemo.get("key1"));				
			}
		}.start();
		new Thread("讀線程3") {
			public void run() {
				System.out.println(readWriteLockDemo.get("key1"));				
			}
		}.start();
	}
}

2.運行效果:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章