Java多線程編程中線程鎖與讀寫鎖的應用示例。本站提示廣大學習愛好者:(Java多線程編程中線程鎖與讀寫鎖的應用示例)文章只能為提供參考,不一定能成為您想要的結果。以下是Java多線程編程中線程鎖與讀寫鎖的應用示例正文
線程鎖Lock
Lock 相當於 以後對象的 Synchronized
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* * Lock lock = new ReentrantLock(); * lock.lock(); lock.unLock(); * 相似於 synchronized,但不克不及與synchronized 混用 */ public class LockTest { public static void main(String[] args) { final Outer outer = new LockTest().new Outer(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (true) { outer.out1("zhangxiaoxiao"); outer.out2("lihuoming"); } } }).start(); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (true) { outer.out1("zhangxiaoxiao"); outer.out2("lihuoming"); } } }).start(); } class Outer { Lock lock = new ReentrantLock(); void out1(String name) { lock.lock(); int len = name.length(); for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); lock.unlock(); } void out2(String name) { lock.lock(); int len = name.length(); for (int i = 0; i < len; i++) { System.out.print(name.charAt(i)); } System.out.println(); lock.unlock(); } } }
讀寫鎖 ReentrantReadWriteLock
讀寫鎖:許可多條線程同時讀;不克不及讀中有寫;不克不及寫中有讀;不克不及寫中有寫
import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /* * 成績:設計一個 緩存機制 的 偽代碼 * 從聚集中讀取數據,讀取不到,就寫入,再斟酌多線程並發的情形 */ public class ReadWriteLockTest2 { private Map<String, Object> data = new HashMap<String, Object>(); private ReadWriteLock lock = new ReentrantReadWriteLock(); //讀寫鎖 public Object getInstance1(String key, Object obj) { lock.readLock().lock(); Object value = null; try { value = data.get(key); if (value == null) {//一條線程進入這裡, lock.readLock().unlock();//讀鎖解了,其他線程便可能也到這了 lock.writeLock().lock();//只能有一條線程到這,寫鎖開啟,要寫入數據了 if (data.get(key) == null) { value = obj; /*先斷定數據,假如不存在,才寫入,,由於 界時當寫鎖消除後,其他 線程,再想寫入時, 斷定到數據存在 ,就跳過了。就不會產生同時寫入的情形 */ data.put(key, value); } lock.writeLock().unlock();//寫完了,解鎖 lock.readLock().lock(); } } finally { lock.readLock().unlock(); } return value; }