Java中的讀寫鎖
阿新 • • 發佈:2019-01-28
import java.util.concurrent.locks.ReentrantReadWriteLock; public class TestRWL { public static void main(String[] args) { RWL r = new RWL(); for (int i = 0; i < 3; i++) { new Thread() { public void run() { while (true) { r.read(); } } }.start(); } for (int i = 0; i < 3; i++) { new Thread() { public void run() { while (true) { r.write((int) (Math.random() * 1000)); } } }.start(); } } } class RWL { private int data = 0;// 共享資料,只能有一個執行緒能寫該資料,但可有多個執行緒同時讀該資料。 private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); public void read() { rwl.readLock().lock();// 上讀鎖,其他執行緒只可讀不可寫 try { System.out.println(Thread.currentThread().getName() + "讀取資料:" + data); Thread.sleep((long) (Math.random() * 1000)); } catch (Exception e) { e.printStackTrace(); } finally { rwl.readLock().unlock();// 釋放讀鎖,最好放在finnaly裡面 } } public void write(int data) { rwl.writeLock().lock();// 上寫鎖,其他執行緒不可讀不可寫 this.data = data; try { System.out.println(Thread.currentThread().getName() + "寫入資料:" + data); Thread.sleep((long) (Math.random() * 1000)); } catch (Exception e) { e.printStackTrace(); } finally { rwl.writeLock().unlock();// 釋放寫鎖,最好放在finnaly裡面 } } }