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

多线程案例:死锁场景一

多线程案例:死锁场景一,第1张

/**

当两个线程或者多个线程互相锁定的情况就叫死锁

避免死锁的原则

解决死锁的基本方法:

当两个线程或线程者多个互相锁定时就形成了死锁。【使用Synchronized关键字 加锁的时候,要避免死锁的发生。】

避免死锁的原则:

? 顺序上锁,反向解锁。

注意:

切记尽量不要使用同步代码块的嵌套!

JAVA线程的API中很多过时方法都构成了死锁,因此不能调用。

?*/

public class DeadLock {

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

????????Object o1 = new Object();

????????Object o2 = new Object();

// t1和t2两个线程共享o1,o2

????????Thread t1 = new MyThread1(o1,o2);

????????Thread t2 = new MyThread2(o1,o2);

????????t1.start();

????????t2.start();

????}

}

class MyThread1 extends Thread{

????Object o1;

????Object o2;

????public MyThread1(Object o1,Object o2){

????????this.o1 = o1;

????????this.o2 = o2;

????}

????public void run(){

????????synchronized (o1){

????????????try {

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

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

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

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

????????????synchronized (o2){

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

????????}

????}

}

class MyThread2 extends Thread {

????Object o1;

????Object o2;

????public MyThread2(Object o1,Object o2){

????????this.o1 = o1;

????????this.o2 = o2;

????}

????public void run(){

????????synchronized (o2){

????????????try {

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

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

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

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

????????????synchronized (o1){

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

????????}

????}

}


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

相关文章: