公平锁和非公平锁
可重入锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
public class ReenterLockDemo {
public static void main(String[] args) {
Phone phone=new Phone();
new Thread(()->{ phone.sendMSG(); },"t1").start(); new Thread(()->{ phone.sendMSG(); },"t2").start();
Thread t3=new Thread(phone); Thread t4=new Thread(phone); t3.start(); t4.start();
} }
class Phone implements Runnable{
public synchronized void sendMSG(){ System.out.println(Thread.currentThread().getId()+"\t invoked sendMSG()"); call(); }
public synchronized void call(){ System.out.println(Thread.currentThread().getId()+"\t invoked call()"); }
Lock lock=new ReentrantLock();
@Override public void run() { get(); }
public void get(){ lock.lock(); try { System.out.println(Thread.currentThread().getId()+"\t get()"); set();
}finally { lock.unlock(); }
} public void set(){ lock.lock(); try { System.out.println(Thread.currentThread().getId()+"\t set()"); }finally { lock.unlock(); } } }
|
读写锁
多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取公共资源应该可以同时进行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
public class ReadWriteLockDemo { public static void main(String[] args) {
MyCache myCache=new MyCache(); for(int i=0;i<10;i++){ final int tempInt=i; new Thread(()->{ myCache.setCache(String.valueOf(tempInt),String.valueOf(tempInt)); },String.valueOf(i)).start(); } for(int i=0;i<10;i++){ final int tempInt=i; new Thread(()->{ myCache.getCache(String.valueOf(tempInt)); },String.valueOf(i)).start(); } } }
class MyCache{
private volatile Map<String,Object> map=new HashMap<>();
ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock();
public void setCache(String key,Object value){ reentrantReadWriteLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t cache"+key+"正在写入!!"); map.put(key,value); System.out.println(Thread.currentThread().getName()+"\t cache"+key+"写入完成!!"); }finally { reentrantReadWriteLock.writeLock().unlock(); }
}
public void getCache(String key){ reentrantReadWriteLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName()+"\t cache正在读取!!"); Object o = map.get(key); System.out.println(Thread.currentThread().getName()+"\t 读取完成!!cache="+o);
}finally { reentrantReadWriteLock.readLock().unlock(); } } public void clear(){ map.clear(); }
}
|