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

线程并发:死锁解决

线程并发:死锁解决,第1张

/**

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

*解决死锁的方法:同步代码块中不要相互嵌套,即,不要相互嵌套锁。

?*/

public class MyDead2 {

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

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

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

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

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

????}

}

//熊掌

class Bear2 {

}

//鱼

class Fish2 {

}

//人

class Person2 extends Thread {

//保证资源只有一份

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

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

????int choose;

????String personName;

????public Person2 (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/3hy1941834.html

相关文章: