概念:
1、在java环境下ReentrantLock和synchronized都是可重入锁
2、非重入锁会导致死锁
3、重入锁,传递给下一个方法,重复使用
重入锁测试代码:
package thread.pool;
/**
* 重入锁、非重入锁
* @author Administrator
*
*/
public class Test5 implements Runnable {
public synchronized void get(){
System.out.println(Thread.currentThread().getId() +"---get()");
set();
}
public synchronized void set(){
System.out.println(Thread.currentThread().getId() +"---set()");
}
@Override
public void run() {
get();
}
public static void main(String[] args) {
Test5 th = new Test5();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
}
}
package thread.pool;
import java.util.concurrent.locks.ReentrantLock;
/**
* 重入锁、非重入锁
* @author Administrator
*
*/
public class Test6 implements Runnable {
ReentrantLock dd = new ReentrantLock();
public void get(){
dd.lock();
System.out.println(Thread.currentThread().getId() +"---get()");
set();
dd.unlock();
}
public void set(){
dd.lock();
System.out.println(Thread.currentThread().getId() +"---set()");
dd.unlock();
}
@Override
public void run() {
get();
}
public static void main(String[] args) {
Test6 th = new Test6();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
new Thread(th).start();
}
}
读写锁的测试代码:
package thread.pool;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
* 读写锁
*
* @author Administrator
*
*/
public class Test7 {
static Map<String, Object> map = new HashMap<>();
static ReentrantReadWriteLock da = new ReentrantReadWriteLock();
static Lock r = da.readLock();
static Lock w = da.writeLock();
public static void get(String key) {
r.lock();
System.out.println(""+key+"正在进行----读----操作-----开始");
try {
Thread.sleep(100);
Object object = map.get(key);
System.out.println(""+key+"-"+object+"正在进行----读---操作-----结束");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
r.unlock();
}
}
public static void set(String key, String value) {
w.lock();
System.out.println(""+key+"-"+value+"正在进行----写----操作-----开始");
try {
Thread.sleep(100);
map.put(key, value);
System.out.println(""+key+"-"+value+"正在进行----写----操作-----结束");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
w.unlock();
}
}
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Test7.get(i+"");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Test7.set(i+"", i+"");
}
}
}).start();
}
}
4、CAS无锁机制
举例:原子类底层实现保证线程安全,就是采用CAS无锁机制,CAS无锁机制效率比有效机制高
5、CAS体系中有三个参数,它包含三个参数CAS(V,E,N):v表示要更新的变量值,E表示预期值,N表示新值。仅当V值等于E值时,才会将V的值设为N,如果V值和E值不同,则说明已经有其他线程做了更新,则当前线程什么都不会做。最后,CAS返回当前V的真实值