package learn.thread;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Demo17 {
static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
static int count = 0;
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
lock.readLock().lock();
try {
System.out.println("线程1准备读取");
Thread.sleep(3000);
System.out.println("线程1读取完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.readLock().unlock();
}
};
Thread t2 = new Thread() {
@Override
public void run() {
lock.writeLock().lock();
try {
System.out.println("线程2准备写入");
Thread.sleep(3000);
System.out.println("线程2写入完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.writeLock().unlock();
}
};
t1.start();
t2.start();
}
}
package learn.thread;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Demo18 {
static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
static int count = 0;
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
lock.writeLock().lock();
try {
System.out.println("线程1准备写入");
Thread.sleep(3000);
System.out.println("线程1写入完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.writeLock().unlock();
}
};
Thread t2 = new Thread() {
@Override
public void run() {
lock.writeLock().lock();
try {
System.out.println("线程2准备写入");
Thread.sleep(3000);
System.out.println("线程2写入完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.writeLock().unlock();
}
};
t1.start();
t2.start();
}
}