读写锁分为读锁和写锁,多个线程获取读锁不互斥,读写锁、写写锁互斥。
package readwrite;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by lenovo on 2018/5/3.
*/
public class Service {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void read() {
try {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "获得读锁:" + System.currentTimeMillis());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
public void write() {
try {
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + "获得写锁:" + System.currentTimeMillis());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
}
package readwrite;
/**
* Created by lenovo on 2018/5/3.
*/
public class Run {
public static void main(String[] args) {
Service service = new Service();
Runnable readRunnable = new Runnable() {
@Override
public void run() {
service.read();
}
};
Runnable writeRunnable = new Runnable() {
@Override
public void run() {
service.write();
}
};
Thread readThread1 = new Thread(readRunnable);
Thread readThread2 = new Thread(readRunnable);
Thread writeThread = new Thread(writeRunnable);
readThread1.start();
readThread2.start();
writeThread.start();
}
}
输出
Thread-0获得读锁:1526039192299
Thread-1获得读锁:1526039192300
Thread-2获得写锁:1526039195300