Lock鎖之重入鎖與讀寫鎖

java哈發表於2020-10-06

Lock鎖

重入鎖ReentrankLock的使用:

package Lock;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrankLocktest {
	Lock lock=new ReentrantLock();
	String[] s= {"A","B","","","",""};
	int index=2;
	public void add(String str) {
		lock.lock();	
		try {		
			s[index]=str;
			index++;	
			System.out.println(Thread.currentThread().getName()+"新增了"+str);	
		}finally {
			lock.unlock();
		}
	}
	public String[] get() {
		return s;		
	}
}


package Lock;
import java.util.Arrays;
public class test {
	public static void main(String[] args) {
		ReentrankLocktest locks=new ReentrankLocktest();
		new Thread(new Runnable() {
			@Override
			public void run() {			
				locks.add("hello");			
			}}).start();	
		new Thread(new Runnable() {
			@Override
			public void run() {			
				locks.add("world");			
			}}).start();
		System.out.println(Arrays.asList(locks.s));
	}
}

讀寫鎖ReentrankReadWriteLock的使用:

  • 一寫多讀同步鎖,讀寫分離,可分別分配讀鎖和寫鎖。
  • 支援多次分配讀鎖,使多個讀鎖併發執行。
    互斥規則:
  • 寫-寫互斥
  • 讀-寫互斥
  • 讀-讀不互斥
package Lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class ReentrankReadWriteLockTest {	
	//讀寫鎖
	private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();
	//讀鎖
	private ReadLock read=lock.readLock();
	//寫鎖
	private WriteLock write=lock.writeLock();
	
	private String value;	
	//寫操作
	public void set(String value) {
		write.lock();	
		try {
			System.out.println(Thread.currentThread().getName()+"寫入:"+value);
			this.value=value;		
		}finally {
			write.unlock();
		}	
	}	
	//讀操作
	public String get() {
		read.lock();
		try {
			System.out.println(Thread.currentThread().getName()+"讀取:"+this.value);
			return this.value;
		}finally {
			read.unlock();
		}		
	}
}

``
package Lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class test1 {

	public static void main(String[] args) {
		ReentrankReadWriteLockTest wr=new ReentrankReadWriteLockTest();
		//建立執行緒池
		ExecutorService es=Executors.newFixedThreadPool(10);
		
		//把任務交給執行緒池
		//寫操作2個執行緒
		es.submit(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<2;i++) {
					wr.set("hello world");
				}			
			}});
		//讀操作8個執行緒
		es.submit(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<8;i++) {
					wr.get();	
				}					
			}			
		});
		//釋放資源
		es.shutdown();
	}
}

相關文章