java readwritelock 非死锁 实例 (对比上文)

public class ReadThread implements Runnable{ TableControl tc; public ReadThread(TableControl tc){ this.tc=tc; }; @Override public void run() { tc.readLock().lock(); System.out.println("ReadThread"); tc.get(); tc.readLock().unlock(); }

}

public class WriteThread implements Runnable{ TableControl tc; public WriteThread(TableControl tc){ this.tc=tc; }; @Override public void run() { tc.writeLock().lock(); System.out.println("WriteThread"); tc.add(100); tc.writeLock().unlock(); }}

import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class TableControl { private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();; private int i = 0; public void get() { System.out.println(i); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } public void add(int v) { i += v; readLock().lock(); System.out.println(System.currentTimeMillis()); get(); System.out.println(System.currentTimeMillis()); readLock().unlock(); System.out.println(i); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } public Lock readLock() { return readWriteLock.readLock(); } public Lock writeLock() { return readWriteLock.writeLock(); }}

public class TestMain { public static void main(String args[]){ TableControl tc=new TableControl(); WriteThread wt=new WriteThread(tc); ReadThread rt=new ReadThread(tc); Thread t1 =new Thread(wt); Thread t2 =new Thread(rt); // t2.start(); t1.start(); } }

思念是对昨天悠长的沉淀和对未来美好的向往。

java readwritelock 非死锁 实例 (对比上文)

相关文章:

你感兴趣的文章:

标签云: