只有读读是并发的,
其它读写,写写,写读都是互斥的哟。
package demo.thread;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyService {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public void read() {
try {
try {
lock.readLock().lock();
System.out.println("Get read lock" + Thread.currentThread().getName()
+ " " + System.currentTimeMillis());
Thread.sleep(1000L);
} finally {
lock.readLock().unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void write() {
try {
try {
lock.writeLock().lock();
System.out.println("Get read lock" + Thread.currentThread().getName()
+ " " + System.currentTimeMillis());
Thread.sleep(1000L);
} finally {
lock.writeLock().unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package demo.thread;
public class ThreadA extends Thread {
private MyService service;
public ThreadA(MyService service) {
super();
this.service = service;
}
@Override
public void run() {
service.read();
}
}
package demo.thread;
public class ThreadB extends Thread {
private MyService service;
public ThreadB(MyService service) {
super();
this.service = service;
}
@Override
public void run() {
service.write();;
}
}
package demo.thread;
public class Run {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
final MyService service = new MyService();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
Thread.sleep(1000);
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
}
}
时间: 2024-09-30 18:18:57