zoukankan      html  css  js  c++  java
  • 多线程死锁(同步套同步,锁套锁)

    多程,互需锁不释放

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

    }

  • 相关阅读:
    2017ecjtu-summer training # 9 HDU 4544
    2017ecjtu-summer training #6 Gym 100952D
    HDU 1241 DFS
    集训队选拔赛 day4
    Educational Codeforces Round 67 (Rated for Div. 2)
    Codeforces Round #566 (Div. 2)
    Codeforces Round #567 (Div. 2)
    Codeforces Round #568 (Div. 2)
    Codeforces Round #569 (Div. 2)
    牛客练习赛48
  • 原文地址:https://www.cnblogs.com/smallfa/p/14595704.html
Copyright © 2011-2022 走看看