標籤:小練習
public class ReadWriteLockDemo {public static void main(String[] args) {final Queue q = new Queue();for (int i = 0; i < 3; i++) {new Thread(new Runnable(){@Overridepublic void run() {while (true) {q.set(new Random().nextInt(1000));}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (true) {q.read();}}}).start();}}}class Queue{private int data;private ReadWriteLock rwl = new ReentrantReadWriteLock();public void set(int data){rwl.readLock().lock();this.data = data;try {System.out.println(Thread.currentThread().getName()+ " ready to write data");Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + " 寫入資料 "+ data);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{rwl.readLock().unlock();}}public void read() {rwl.writeLock().lock();try {System.out.println(Thread.currentThread().getName()+ " ready to read data");Thread.sleep(1000);System.out.println(Thread.currentThread().getName() + " 擷取dao資料 "+ data);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{rwl.writeLock().unlock();}}}
本文出自 “要麼拚命,要麼滾回去!” 部落格,請務必保留此出處http://jiangzuun2014.blog.51cto.com/8732469/1538356