zoukankan      html  css  js  c++  java
  • 多线程死锁发生情景之一:同步的嵌套

    /*
      死锁:常见情景之一:同步的嵌套。
    
    */
    class Ticket implements Runnable {
        private  int num = 100;
        Object obj = new Object();
        boolean flag = true;
        public void run() {
            if(flag) {
                while(true) {
                    synchronized(obj) {
                        show();
                    }
                }        
            }
                
            else {        
                while(true) {
                    this.show();
                }        
            }         
                    
        }
    
        public synchronized void show() {
    
            synchronized(obj) {
                if(num>0) {
                    try{Thread.sleep(10);}catch (InterruptedException e){}
                    
                    System.out.println(Thread.currentThread().getName()+".....sale...."+num--);
                }
            }
        }
    }
    
    
    class DeadLockDemo {
    public static void main(String[] args) { Ticket t = new Ticket(); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try{Thread.sleep(10);}catch(InterruptedException e){} t.flag = false; t2.start(); } }
  • 相关阅读:
    常用数列
    sqrt
    树状数组
    hash
    P1102 A-B数对
    codevs 1795 金字塔 2
    P2296 寻找道路
    [USACO16JAN]子共七Subsequences Summing to Sevens
    P3397 地毯
    关于调用&&传址
  • 原文地址:https://www.cnblogs.com/wgDream/p/7300948.html
Copyright © 2011-2022 走看看