为了提高性能,java提供了读写锁,
读锁: 在读的地方使用读锁,可以多个线程同时读。
写锁: 在写的地方使用写锁,只要有一个线程在写,其他线程就必须等待
例子:
public static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public static Lock readLock = readWriteLock.readLock();
public static Lock writeLock = readWriteLock.writeLock();
public static void readWriteLock(){
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
readLock.lock();
System.out.println("T1 Read!");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("T1 unLock!");
readLock.unlock();
}
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
readLock.lock();
System.out.println("T2 Read!");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("T2 unLock!");
readLock.unlock();
}
}
});
Thread t3 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
writeLock.lock();
System.out.println("T3 write!");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
System.out.println("T3 unLock!");
writeLock.unlock();
}
}
});
t1.start();
t2.start();
t3.start();
}