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--);
                }
            }
        }
    }
  • 相关阅读:
    MQ消息队列(2)—— Java消息服务接口(JMS)
    MQ消息队列(1)—— 概念和使用场景
    SpringBoot — HelloWorld开发部署
    redis的配置文件介绍
    Redis info 参数详解
    10 分钟彻底理解 Redis 的持久化和主从复制
    Docker Yearning + Inception SQL审核平台搭建
    Inception SQL审核注解
    运行python脚本后台执行
    解决yum [Errno 256] No more mirrors to try
  • 原文地址:https://www.cnblogs.com/cxmsky/p/2860380.html
Copyright © 2011-2022 走看看