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;
            }
        }
        
    }
  • 相关阅读:
    第06课:GDB 常用命令详解(下)
    第05课:GDB常用命令详解(中)
    第04课:GDB常用命令详解(上)
    第03课:GDB常用的调试命令概览
    第02课:启动GDB调试
    第01课:调试信息与调试原理
    数据库(二)
    数据库笔记(一)
    acedSSGet 翻译
    ObjectARX动态添加AutoCAD传统下拉菜单入门篇(一)
  • 原文地址:https://www.cnblogs.com/lijins/p/10054988.html
Copyright © 2011-2022 走看看