多线程的死锁——T2219

package 对象及变量的并发访问2;

/**
 * 多线程的死锁
 *   java多线程死锁是一个经典的多线程问题,因为不同线程都在等待根本不可能被释放的锁,
 * 从而导致所有任务都无法继续完成。在多线程技术中,“死锁”是必须避免的,因为这回造成下线程“假死”。
 *
 */

class DealThread implements Runnable{
    public String username;
    public  Object object=new Object();
    public Object object2=new Object();

    public  void setFlag(String username){
            this.username=username;
    }

    @Override
    public  void run() {
        if ((username.equals("a"))){
            synchronized (object){
                try {
                    System.out.println("username="+username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object2){
                    System.out.println("按object->object2代码执行顺序");
                }
            }
        }

        if(username.equals("b")){
            synchronized (object2){
                try {
                    System.out.println("username="+username);
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (object){
                    System.out.println("按object2->object代码执行顺序");
                }
            }
        }
    }
}

class RunT2219{
    public RunT2219(){
        try {
            DealThread dealThread=new DealThread();

            dealThread.setFlag("a");
            Thread thread=new Thread(dealThread);
            thread.start();

            Thread.sleep(100);

            dealThread.setFlag("b");
            Thread thread1=new Thread(dealThread);
            thread1.start();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class T2219 {
    public static void main(String[] args) {
        RunT2219 runT2219=new RunT2219();
    }
}

在这里插入图片描述

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页