package thread.lock;
public class Test {
public static void main(String[] args) {
final Printer printer = new Printer();
Thread thread1 = new Thread(){
@Override
public void run() {
printer.read("thread1 read...");
printer.write("thread1 write...");
}
};
Thread thread2 = new Thread(){
@Override
public void run() {
printer.read("thread2 read...");
printer.write("thread2 write...");
}
};
thread1.start();
thread2.start();
}
}
package thread.lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Printer {
ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* 读操作
* @author JIANGBIN
* @param str
*/
public void read(String str){
lock.readLock().lock();//读锁1
try{
for (int i = 0; i < 3; i++) {
try {
System.out.println(str);
Thread.sleep(200);//暂停100ms,不释放锁,以便更好的观察输出结果
} catch (InterruptedException e) {
}
}
}finally{
lock.readLock().unlock();//解锁,要放在finnall块里面
}
}
/**
* 写操作
* @author JIANGBIN
* @param str
*/
public void write(String str){
lock.writeLock().lock();//写锁
try{for (int i = 0; i < 3; i++) {
try {
System.out.println(str);
Thread.sleep(100);//暂停100ms,不释放锁,以便更好的观察输出结果
} catch (InterruptedException e) {
}
}
}finally{
lock.writeLock().unlock();//解锁
}
}
}
输出结果:
thread1 read...
thread2 read...
thread2 read...
thread1 read...
thread2 read...
thread1 read...
thread2 write...
thread2 write...
thread2 write...
thread1 write...
thread1 write...
thread1 write...
总结:读锁之间可以变法访问,读锁和写锁直接互斥,写锁和写锁之间互斥