1、可重入锁:
也称为递归锁,当外层函数获得该锁之后,内层递归函数仍有获取该锁的代码,结果不受影响;
java中的synchronized ReentrantLock都是可重的
举例:
public class Test implements Runnable{
public synchronized void get(){
System.out.println(Thread.currentThread().getId());
set();
}
public synchronized void set(){
System.out.println(Thread.currentThread().getId());
}
@Override
public void run() {
get();
}
public static void main(String[] args) {
Test ss=new Test();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
}
}
public class Test implements Runnable {
ReentrantLock lock = new ReentrantLock();
public void get() {
lock.lock();
System.out.println(Thread.currentThread().getId());
set();
lock.unlock();
}
public void set() {
lock.lock();
System.out.println(Thread.currentThread().getId());
lock.unlock();
}
@Override
public void run() {
get();
}
public static void main(String[] args) {
Test ss = new Test();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
}
}
2、自旋锁
一个线程直接循环执行一个任务,不触发临界条件,另一个线程控制临界条件,另一个线程执行时可以使前一个线程停止执行。
例子:
public class SpinLock {
private AtomicReference<Thread> sign =new AtomicReference<>();
public void lock(){
Thread current = Thread.currentThread();
while(!sign .compareAndSet(null, current)){
}
}
public void unlock (){
Thread current = Thread.currentThread();
sign .compareAndSet(current, null);
}
}
public class Test implements Runnable{ |
03 | public synchronized void get(){ |
04 | System.out.println(Thread.currentThread().getId()); |
08 | public synchronized void set(){ |
09 | System.out.println(Thread.currentThread().getId()); |
16 | public static void main(String[] args) { |
18 | new Thread(ss).start(); |
19 | new Thread(ss).start(); |
20 | new Thread(ss).start(); |
01 | public class Test implements Runnable { |
02 | ReentrantLock lock = new ReentrantLock(); |
06 | System.out.println(Thread.currentThread().getId()); |
13 | System.out.println(Thread.currentThread().getId()); |
22 | public static void main(String[] args) { |
24 | new Thread(ss).start(); |
25 | new Thread(ss).start(); |
26 | new Thread(ss).start(); |