Dict.CN 在线词典, 英语学习, 在线翻译 ------------- MyGitee 朱秋贵内科诊所 My腾云code

多线程死锁(同步套同步,锁套锁)

多程,互需锁不释放

同时
窗口1:先object锁,再this锁,票数-1
窗口2:先this锁,再object锁,票数-1

 

public class TickerThread3 implements Runnable {

private static int count=100;
private Boolean flag=true;
private Object object=new Object();


@Override
public void run() {
  if(flag){
    while (count>0){
      synchronized (object){
    try {
      Thread.sleep(10);
    }catch (Exception e)
    {

    }
    ticket();
    }
  }
  }else {
    while (count>0){
    ticket();
  }
  }
  }


public synchronized void ticket(){
  synchronized (object){
    try {
      Thread.sleep(10);
    }catch (Exception e)
    {

    }
  }


  if(count>0){
    System.out.println(Thread.currentThread().getName()+",正在出票第【"+(100-count+1)+"】张");
    count--;
  }

}

 

 

public static void main(String arg[])
{
  TickerThread3 tickerThread=new TickerThread3();
  new Thread(tickerThread,"售票机1号").start();
  try {
    Thread.sleep(40);
    tickerThread.flag=false;
  }catch (Exception e)
  {

  }
    new Thread(tickerThread,"售票机2号").start();
  }

}

 

 

 

 

 

posted @ 2021-03-30 10:36  cn2023  阅读(57)  评论(0编辑  收藏  举报