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);
writeLock().lock();
System.out.println(System.currentTimeMillis());
add(50);
writeLock().unlock();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void add(int v) {
i += v;
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();
}
}