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();
      }

    }

  • 相关阅读:
    雅虎天气API调用
    HttpOperater
    HttpOperater-模拟HTTP操作类
    页面局部加载,适合Ajax Loading场景(Demo整理)
    FTPHelper-封装FTP的相关操作
    使用SOCKET实现TCP/IP协议的通讯
    IIS目录禁止执行权限
    Oracle10g 安装步骤
    SQL Server 2008、SQL Server 2008R2 自动备份数据库
    SQL列转行
  • 原文地址:https://www.cnblogs.com/smallfa/p/14595704.html
Copyright © 2011-2022 走看看