当前位置: 首页>后端>正文

线程并发:死锁问题

线程并发:死锁问题,第1张

/**

*死锁例子:鱼和熊不可兼得

?*

*死锁形成的原因:多个线程各自占有一个资源,并且相互等待其他线程占有的资源才能运行,

*从而导致另个或者多个线程都在等待对方释放资源,都停止了执行。

*某一个同步代码块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。

?*

*执行结果:两个线程一直阻塞,都在等在对方释放锁,结果导致死锁。

?*/

public class MyDead {

????public static void main(String[] args) throws InterruptedException {

Person personA = new Person(0, "猎人A");

Person personB = new Person(1, "猎人B");

????????personA.start();

????????personB.start();

????}

}

//熊掌

class Bear {

}

//鱼

class Fish {

}

//人

class Person extends Thread {

//保证资源只有一份

????public static Bear bear = new Bear();

????public static Fish fish = new Fish();

????int choose;

????String personName;

????public Person (int choose, String personName) {

????????this.choose = choose;

????????this.personName = personName;

????}

????@Override

????public void run() {

//捕猎

????????try {

????????????this.hunting();

????????} catch (InterruptedException e) {

????????????e.printStackTrace();

????????}

????}

//捕猎方法

????private void hunting() throws InterruptedException {

????????if (choose == 0) {

????????????synchronized (bear) {

System.out.println(personName + "想捕捉熊");

????????????????Thread.sleep(1000);

????????????????synchronized (fish) {

System.out.println(personName + "想捕捉鱼");

????????????????}

????????????}

????????} else {

????????????synchronized (fish) {

System.out.println(personName + "想捕捉鱼");

????????????????Thread.sleep(1000);

????????????????synchronized (bear) {

System.out.println(personName + "想捕捉熊");

????????????????}

????????????}

????????}

????}

}


https://www.xamrdz.com/backend/3yg1934405.html

相关文章: