zoukankan      html  css  js  c++  java
  • synchronized 同步代码块,售票问题

    package cn.ljs.FristSync;
    
    
    public class SalerDemo extends Thread {
    	
    	static int tickets = 1000;
    	String name;
    	static Object lock = new Object();
    	public SalerDemo(String name) {
    		this.name = name;
    	}
    	public void run(){
    		
    		while(true){
    			
    			synchronized (lock) {
    				if (tickets < 1) {
    					return ;
    				}
    				System.out.println(name + ": " + tickets);
    				tickets--;
    			}
    		}
    	}
    	
    	public static void main(String[] args) {
    		Thread t1 = new SalerDemo("saler1");
    		Thread t2 = new SalerDemo("saler2");
    		Thread t3 = new SalerDemo("saler3");
    		t1.start();
    		t2.start();
    		t3.start();
    		
    	}
    	
    	
    }
    

     

    建立票池 

    package cn.ljs.FristSync;
    
    public class SalerDemo01 extends Thread{
        
        private String name;
        private TicketsPool pool;
        
        public SalerDemo01(String name, TicketsPool pool){
            this.name = name;
            this.pool = pool;
        }
        
        public void run(){
            while (true){
                int num = pool.getTickets();
                if (num != 0) {
                    System.out.println(name+"卖了"+num);
                }else {
                    return;
                }
            }
            
        }
        
        public static void main(String[] args) {
            
            TicketsPool pool = new TicketsPool();
            SalerDemo01 saler1 = new SalerDemo01("01", pool);
            SalerDemo01 saler2 = new SalerDemo01("02", pool);
            SalerDemo01 saler3 = new SalerDemo01("03", pool);
            
            saler1.start();
            saler2.start();
            saler3.start();
            
            
        }
        
    }
    
    
    class TicketsPool{
        
        private int num = 100;
        public int getTickets(){
            
            synchronized (this) {
                int tmp = num;
                num--;
                return tmp > 0 ? tmp:0;
            }
        }
        
    }
  • 相关阅读:
    类和对象
    类和对象1
    常见的子串问题
    常见的算法问题全排列
    第六届蓝桥杯java b组第五题
    第六届蓝桥杯java b组第四题
    第六届蓝桥杯java b组第三题
    第六届蓝桥杯java b组第二题
    第六届蓝桥杯java b组第一题
    第八届蓝桥杯java b组第三题
  • 原文地址:https://www.cnblogs.com/lijins/p/10054988.html
Copyright © 2011-2022 走看看