zoukankan      html  css  js  c++  java
  • JAVA synchronized 线程经典 生产者消费者 两个完全不同的实现的方式

    package sell_ticket;
    
    public class ThreadTicket {
    
          public static void main(String[] args) {   
                MyThread m = new MyThread();        
                Thread t1 = new Thread(m);
                Thread t2 = new Thread(m);
                Thread t3 = new Thread(m);
                t1.start();
                t2.start();
                t3.start();
            }        
    }
    
    class MyThread implements Runnable{
        private int ticket=100;
        
        
    //synchronized
        public void run(){
            while(true){     
                  try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
                  }
                //用synchronized包起来,形成同步代码块,但后来发现用不用其实一样
                synchronized(this){
                    if(ticket>0){
                        System.out.println(Thread.currentThread().getName()+"出售了"+ticket);            
                        ticket--;
                    }
                }
                
            }
        }
        
        
    }
    
    以上还有另一个写法,synchronized一个方法:
    
    class Test implements Runnable
    {
        //票的总数
        private int ticket=20;
        public void run()
        {
           //50只是用来循环,无意义
          for(int i=1;i<50;i++)
            {
                try {
                    //休眠1s秒中,为了使效果更明显,否则可能出不了效果
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                this.sale();
            }
        }
        public synchronized void sale()
        {
                if(ticket>0)
                {
                   //很有意思的一个发现,如果用System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket--+"号票"); 哪怕不用synchronized,重复卖票的现像也会低很多
                  
                    System.out.println(Thread.currentThread().getName()+"号窗口卖出"+this.ticket+"号票");
                    ticket--;
                }
        }
        
        public static void main(String args[])
        {
            Test mt=new Test();
            //基于火车票创建三个窗口
            new Thread(mt,"a").start();
            new Thread(mt,"b").start();
            new Thread(mt,"c").start();
        } 
    }




    第二种,采用堆栈的方式:
     
    
    
    
    
    
    
    
    
    
    
    
       
    
  • 相关阅读:
    EF 错误解决
    TortoiseHg 学习笔记 (转)
    Mysql 命令行 使用 (转)
    2017-9-3 时间字符串格式化(转)
    2017-8-25 c# 获取url参数的五种方法(转)
    alert 的使用方法
    表单关键字查询写法
    Mysql和Mysqli的区别
    php MySQL中 增、删、改、查的写法格式
    一维、二维数组 与 常用的返回数组 以及 fetch_all与fetch_row的区别
  • 原文地址:https://www.cnblogs.com/xiaowangba/p/6314507.html
Copyright © 2011-2022 走看看