一、锁对象( ReentrantLock )
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test2 {
public static void main(String[] args) {
Output1 output = new Output1();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.print("hello");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while(true){
output.print("world");
}
}
}).start();
}
}
class Output1{
//创建了锁对象
Lock lock = new ReentrantLock();
public void print(String name){
lock.lock();
try {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
System.out.println();
}
}
二、读写锁格式(
ReentrantReadWriteLock)
缓存操作,读写锁操作
import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Test3 {
/**
* 修改数据是只能一个线程进来访问
* 但是如果是读数据,所有线程都可以访问
* 读写锁的机制
*/
private HashMap<String,String> hm = new HashMap<String,String>();
//创建读写锁
private ReentrantReadWriteLock rrw = new ReentrantReadWriteLock();
private String value = null;
public String getDate(String key){
/*value = hm.get(key);
if(value == null){
value = "hello";//将来通过其他资源获取
hm.put(key, value);
}
return value;*/
rrw.readLock().lock();//上读锁
try {
value = hm.get(key);//大家都能来读
if(value == null){
//要进行写操作
rrw.readLock().unlock();//解读锁
rrw.writeLock().lock();//上写锁
try {
/*
* 大家都能进入到第一个if都能做解读锁上写锁的操作,
* 只不过上写锁得等待上一个线程解写锁,
* 大家都能进入到第一个try,
* 所以在这里需要再次进行if判断
*/
if(value == null){
value = "hello";
hm.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
rrw.writeLock().unlock();//解写锁
rrw.readLock().lock();//上读锁
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
rrw.readLock().unlock();//解读锁
}
return value;
}
}