多程,互需锁不释放

同时
窗口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();
  }

}

 

 

 

 

 

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

相关文章:

  • 2022-02-16
  • 2022-12-23
  • 2021-08-28
  • 2021-09-14
  • 2022-02-22
  • 2021-08-08
  • 2021-09-17
  • 2022-12-23
猜你喜欢
  • 2021-07-26
  • 2022-12-23
  • 2021-11-01
  • 2021-09-14
  • 2022-01-18
  • 2021-10-14
  • 2021-06-15
相关资源
相似解决方案