3.10、活跃性、死锁、哲学家就餐、活锁、饥饿

死锁

有这样的情况:一个线程需要同时获得多把锁,这时就容易发生死锁
t1线程获得A对象锁,接下来想获取B对象的锁,t2线程获得B对象锁,接下来想要获取A对象

例:

		Object A = new Object();
        Object B = new Object();

        new Thread(() -> {
            synchronized (A) {
                log.debug("lock A");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B) {
                    log.debug("lock B");
                    log.debug("do..");
                }
            }
        }, "t1").start();
        new Thread(() -> {
            synchronized (B) {
                log.debug("lock B");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (A) {
                    log.debug("lock A");
                    log.debug("do..");
                }
            }
        }, "t2").start();

输出

2022/03/06-18:20:57.484 [t1] c.Test1 - lock A
2022/03/06-18:20:57.484 [t2] c.Test1 - lock B

定位死锁

  • 检测死锁可以使用jconsole工具,或使用jps定位进程id,在用jstack定位死锁
D:\self\IdeaProjects\juc-test\target\classes>jps
19764 Test1
14636 RemoteMavenServer36
14988
17052 Launcher
18636 Jps
D:\self\IdeaProjects\juc-test\target\classes>jstack 19764
2022-03-06 18:22:58
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.162-b12 mixed mode):

"DestroyJavaVM" #14 prio=5 os_prio=0 tid=0x0000000003343800 nid=0x210 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"t2" #13 prio=5 os_prio=0 tid=0x000000001fb44000 nid=0x299c waiting for monitor entry [0x000000002031f000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at deadlock.Test1.lambda$main$1(Test1.java:39)
        - waiting to lock <0x000000076decb288> (a java.lang.Object)
        - locked <0x000000076decb298> (a java.lang.Object)
        at deadlock.Test1$$Lambda$2/245672235.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:748)

"t1" #12 prio=5 os_prio=0 tid=0x000000001fb69800 nid=0x160 waiting for monitor entry [0x000000002021f000]
   java.lang.Thread.State: BLOCKED (on object monitor)
        at deadlock.Test1.lambda$main$0(Test1.java:25)
        - waiting to lock <0x000000076decb298> (a java.lang.Object)
        - locked <0x000000076decb288> (a java.lang.Object)
        at deadlock.Test1$$Lambda$1/1321640594.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:748)

"Service Thread" #11 daemon prio=9 os_prio=0 tid=0x000000001ec78000 nid=0xe9c runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread3" #10 daemon prio=9 os_prio=2 tid=0x000000001ebe3800 nid=0x48d4 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread2" #9 daemon prio=9 os_prio=2 tid=0x000000001ebdf000 nid=0x4998 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #8 daemon prio=9 os_prio=2 tid=0x000000001ebda000 nid=0x3eb0 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #7 daemon prio=9 os_prio=2 tid=0x000000001ebd9800 nid=0x19e8 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Monitor Ctrl-Break" #6 daemon prio=5 os_prio=0 tid=0x000000001ebd6800 nid=0x4f58 runnable [0x000000001f26e000]
   java.lang.Thread.State: RUNNABLE
        at java.net.SocketInputStream.socketRead0(Native Method)
        at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
        at java.net.SocketInputStream.read(SocketInputStream.java:171)
        at java.net.SocketInputStream.read(SocketInputStream.java:141)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
        - locked <0x000000076d2c4d08> (a java.io.InputStreamReader)
        at java.io.InputStreamReader.read(InputStreamReader.java:184)
        at java.io.BufferedReader.fill(BufferedReader.java:161)
        at java.io.BufferedReader.readLine(BufferedReader.java:324)
        - locked <0x000000076d2c4d08> (a java.io.InputStreamReader)
        at java.io.BufferedReader.readLine(BufferedReader.java:389)
        at com.intellij.rt.execution.application.AppMainV2$1.run(AppMainV2.java:47)

"Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x000000001ea91000 nid=0x246c waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x000000001ea90800 nid=0x4ba4 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=1 tid=0x000000001ea21800 nid=0x1528 in Object.wait() [0x000000001eeff000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076d008ec0> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
        - locked <0x000000076d008ec0> (a java.lang.ref.ReferenceQueue$Lock)
        at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
        at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:212)

"Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x000000000343a000 nid=0x4ac0 in Object.wait() [0x000000001e9ff000]
   java.lang.Thread.State: WAITING (on object monitor)
        at java.lang.Object.wait(Native Method)
        - waiting on <0x000000076d006b68> (a java.lang.ref.Reference$Lock)
        at java.lang.Object.wait(Object.java:502)
        at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
        - locked <0x000000076d006b68> (a java.lang.ref.Reference$Lock)
        at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"VM Thread" os_prio=2 tid=0x000000001cb39000 nid=0x4fcc runnable

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x0000000003359000 nid=0x4610 runnable

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x000000000335a800 nid=0x1c4c runnable

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x000000000335c800 nid=0x31d8 runnable

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x000000000335e000 nid=0x4df0 runnable

"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x0000000003360000 nid=0x4410 runnable

"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x0000000003362800 nid=0x41d4 runnable

"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x0000000003365800 nid=0x3cd8 runnable

"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x0000000003366800 nid=0x4088 runnable

"VM Periodic Task Thread" os_prio=2 tid=0x000000001ecea800 nid=0x4898 waiting on condition

JNI global references: 316


Found one Java-level deadlock:
=============================
"t2":
  waiting to lock monitor 0x000000001cb40da8 (object 0x000000076decb288, a java.lang.Object),
  which is held by "t1"
"t1":
  waiting to lock monitor 0x000000001cb42d48 (object 0x000000076decb298, a java.lang.Object),
  which is held by "t2"

Java stack information for the threads listed above:
===================================================
"t2":
        at deadlock.Test1.lambda$main$1(Test1.java:39)
        - waiting to lock <0x000000076decb288> (a java.lang.Object)
        - locked <0x000000076decb298> (a java.lang.Object)
        at deadlock.Test1$$Lambda$2/245672235.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:748)
"t1":
        at deadlock.Test1.lambda$main$0(Test1.java:25)
        - waiting to lock <0x000000076decb298> (a java.lang.Object)
        - locked <0x000000076decb288> (a java.lang.Object)
        at deadlock.Test1$$Lambda$1/1321640594.run(Unknown Source)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.
  • 避免死锁要注意加锁顺序
  • 另外如果由于某个线程进入了死循环,导致其他线程一直等待,对于这种情况linux下可以通过top先定位到CPU占用高的Java进程,再利用top -Hp 进程id来定位是哪个线程,最后在用jstack排查

哲学家就餐问题

在这里插入图片描述
有五位哲学家,未做在圆桌旁

  • 他们只做两件事情,思考和吃饭,思考一会吃口饭,吃完饭后接着思考
  • 吃饭时要用两根筷子吃,桌上一共5根筷子,美味哲学家左右手各有一根筷子
  • 如果筷子被身边的人拿着,自己就等待

筷子类

public class Chopstick {

    String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Chopstick{" +
                "name='" + name + '\'' +
                '}';
    }
}

哲学家类

public class Philosoper extends Thread {

    Chopstick left;
    Chopstick right;

    public Philosoper(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    public void eat() {
        try {
            log.debug("eating");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            synchronized (left) {
                synchronized (right) {
                    eat();
                }
            }
        }
    }
}

测试

	public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");
        new Philosoper("苏格拉底", c1, c2).start();
        new Philosoper("柏拉图", c2, c3).start();
        new Philosoper("亚里士多德", c3, c4).start();
        new Philosoper("赫拉克勒斯", c4, c5).start();
        new Philosoper("阿基米德", c5, c1).start();
    }

输出

2022/03/06-21:53:30.380 [苏格拉底] c.Philosoper - eating
2022/03/06-21:53:30.380 [亚里士多德] c.Philosoper - eating
2022/03/06-21:53:31.386 [阿基米德] c.Philosoper - eating
// 卡住了

使用jconsole检查死锁
在这里插入图片描述

这种线程没有按预期结束,执行不下去的情况,归类为【活跃性】问题,除了死锁以外,还有活锁和饥饿者两种情况

活锁

活锁出现在两个线程互相改变对方的结束条件,最后谁也无法结束

static volatile int count = 10;

    public static void main(String[] args) {
        new Thread(() -> {
            while (count > 0) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count--;
                log.debug("count:{}",count);
            }
        },"t1").start();
        new Thread(() -> {
            while (count < 20) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count++;
                log.debug("count:{}",count);
            }
        },"t2").start();
    }

饥饿

很多教程中把饥饿定义为,一个线程优先级太低,是中得不到CPU调度执行,也不能够结束,饥饿的情况不易演示,讲读写锁会涉及饥饿问题

下面是一个线程饥饿的例子,先看看使用顺序加锁方式解决之前的死锁问题
在这里插入图片描述
顺序加锁的解决方案
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值