zoukankan      html  css  js  c++  java
  • synchronized(七)

    package com.bjsxt.base.sync006;

    /**
    * 死锁问题,在设计程序时就应该避免双方相互持有对方的锁的情况
    * @author alienware
    *
    */
    public class DeadLock implements Runnable{

    private String tag;
    private static Object lock1 = new Object();
    private static Object lock2 = new Object();

    public void setTag(String tag){
    this.tag = tag;
    }


    public void run() {
    if(tag.equals("a")){
    synchronized (lock1) {
    try {
    System.out.println("当前线程 : " + Thread.currentThread().getName() + " 进入lock1执行");
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    synchronized (lock2) {
    System.out.println("当前线程 : " + Thread.currentThread().getName() + " 进入lock2执行");
    }
    }
    }
    if(tag.equals("b")){
    synchronized (lock2) {
    try {
    System.out.println("当前线程 : " + Thread.currentThread().getName() + " 进入lock2执行");
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    synchronized (lock1) {
    System.out.println("当前线程 : " + Thread.currentThread().getName() + " 进入lock1执行");
    }
    }
    }
    }

    public static void main(String[] args) {

    DeadLock d1 = new DeadLock();
    d1.setTag("a");
    DeadLock d2 = new DeadLock();
    d2.setTag("b");

    Thread t1 = new Thread(d1, "t1");
    Thread t2 = new Thread(d2, "t2");

    t1.start();
    try {
    Thread.sleep(500);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    t2.start();
    }


    }

    运行结果:

    当前线程 : t1 进入lock1执行
    当前线程 : t2 进入lock2执行

  • 相关阅读:
    舵机驱动-GPIO MG995 STM32
    Ymodem协议-接收
    IAP注意事项
    stm32系统时钟配置,标准库v3.5
    FREERTOS移植(MDK 、STM32F103)
    C语言常量后缀
    回调函数
    运算符记忆口诀
    C语言函数指针
    frp 搭建内网穿透
  • 原文地址:https://www.cnblogs.com/tsdblogs/p/8760308.html
Copyright © 2011-2022 走看看