zoukankan      html  css  js  c++  java
  • 死锁:同步中嵌套同步,但锁不同,示例二:

    class DeadLockDemo
    {
        public static void main(String[] args)
        {
            Ticket ticket = new Ticket();
            for(int i = 1;i<10;i++)
            {
                new Thread(ticket,"thread--00"+ i +"--").start();
                try
                {
                    Thread.sleep(10);
                }
                catch(Exception e)
                {
                    System.out.println(e.getMessage());
                }
                ticket.flag = !ticket.flag;
            }
        }
    }

    class Ticket implements Runnable
    {
        private int num = 10000;
        Object object = new Object();
        boolean flag = true;
        
        public void run()
        {
            if(flag)
            {
                while(true)
                {
                    synchronized(object)
                    {
                        sale();
                    }
                }
            }
            else
            {
                while(true)
                {
                    sale();
                }
            }        
        }
        
        public synchronized void sale()
        {
            synchronized(object)
            {
                if(num>0)
                {
                    try
                    {
                        Thread.sleep(10);
                    }
                    catch(Exception e)
                    {
                        
                    }
                    
                    System.out.println(Thread.currentThread().getName()+" .. sale .. "+num--);
                }
            }
        }
    }
  • 相关阅读:
    获取exe和dll里面的资源
    [C++] 反编译器
    再一次利用with as 优化SQL
    编码指南:寻找科学中的艺术
    对手机支付安全机制的思考
    用adblock过滤页面上固定位置的悬浮窗
    git卡在Resolving deltas 100%的解决办法
    十字路口的程序员
    hdu 2555
    hdu 1864
  • 原文地址:https://www.cnblogs.com/cxmsky/p/2860380.html
Copyright © 2011-2022 走看看