java中可重入锁和自旋锁

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{
02 
03    public synchronized void get(){
04        System.out.println(Thread.currentThread().getId());
05        set();
06    }
07 
08    public synchronized void set(){
09        System.out.println(Thread.currentThread().getId());
10    }
11 
12    @Override
13    public void run() {
14        get();
15    }
16    public static void main(String[] args) {
17        Test ss=new Test();
18        new Thread(ss).start();
19        new Thread(ss).start();
20        new Thread(ss).start();
21    }
22}
01public class Test implements Runnable {
02    ReentrantLock lock = new ReentrantLock();
03 
04    public void get() {
05        lock.lock();
06        System.out.println(Thread.currentThread().getId());
07        set();
08        lock.unlock();
09    }
10 
11    public void set() {
12        lock.lock();
13        System.out.println(Thread.currentThread().getId());
14        lock.unlock();
15    }
16 
17    @Override
18    public void run() {
19        get();
20    }
21 
22    public static void main(String[] args) {
23        Test ss = new Test();
24        new Thread(ss).start();
25        new Thread(ss).start();
26        new Thread(ss).start();
27    }
28}
    原文作者:java锁
    原文地址: http://www.cnblogs.com/hy87/p/8859021.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞