欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

各种锁的理解

程序员文章站 2022-05-22 12:42:24
...

公平锁和非公平锁

公平锁:非常公平,线程不能插队
非公平锁,线程可以插队
Lock lock = new ReentrantLock();就是非公平锁

可重入锁

同步方法嵌套,线程在拿到外边锁了,也会获取到里边的锁,
各种锁的理解

synchronized锁

public class Demo1 {

    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            phone.send();
        },"a").start();

        new Thread(()->{
            phone.send();
        },"b").start();
    }
}

class Phone{
    public synchronized void send(){
        System.out.println(Thread.currentThread().getName() + "---send");
        call();
    }

    public synchronized void call(){
        System.out.println(Thread.currentThread().getName() + "----call");
    }
}

Lock锁

public class Demo1 {

    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(()->{
            phone.send();
        },"a").start();

        new Thread(()->{
            phone.send();
        },"b").start();
    }
}

class Phone{
    Lock lock = new ReentrantLock();

    public  void send(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "---send");
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public  void call(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "----call");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

自旋锁

各种锁的理解

死锁

各种锁的理解

public class DiedLockDemo {
    public static void main(String[] args) {
        String strA = "strA";
        String strB = "strB";
        new Thread(new MyDied(strA, strB)).start();
        new Thread(new MyDied(strB, strA)).start();
    }
}


class MyDied implements Runnable{
    private String strA;
    private String strB;

    public MyDied(String strA, String strB) {
        this.strA = strA;
        this.strB = strB;
    }

    @Override
    public void run() {
        synchronized (strA) {
            System.out.println(Thread.currentThread().getName() + "---strA");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (strB) {
                System.out.println(Thread.currentThread().getName() + "---strB");
            }
        }
    }
}

查看死锁
在死锁情况下,idea的Terminal窗口

各种锁的理解
idea的Terminal窗口输入jps -l ,查询进程号
各种锁的理解
然后在输入:jstack 进程号
各种锁的理解
信息拉到最下边就可以看到死锁的信息
各种锁的理解

相关标签: 多线程