0

java | 活跃性

 1 year ago
source link: https://benpaodewoniu.github.io/2022/12/19/java128/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

java | 活跃性

2022-12-19java进阶多线程基础

1

线程的活跃性有 3 种情况

一个线程需要同时获得多把锁,这样就容易发生死锁了。

  • t1 线程获得 A 对象的锁,接下来想获取 B 对象的锁
  • t2 线程获得 B 对象的锁,接下来想获取 A 对象的锁
package com.redisc;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.Run")
public class Run {

static volatile int count = 10;

public static void main(String[] args) throws Exception {
new Thread(() -> {
while (count > 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
log.debug("count {}", count);
}
}).start();

new Thread(() -> {
while (count < 20) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
log.debug("count {}", count);
}
}).start();
}

}

两个线程争相创造条件。

其中一个线程一直处于非运行状态。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK