码迷,mamicode.com
首页 > 其他好文 > 详细

饿汉单例模式实例——取快递

时间:2018-05-01 14:05:25      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:let   package   img   sage   sys   bsp   on()   span   cep   

package single;
import java.util.*;
public class CourierThread extends Thread{

    String couriers[]={"顺丰快递","申通快递","圆通快递","韵达快递","天天快递"};
    String threadName=null;
    public CourierThread(String name) {
        // TODO Auto-generated constructor stub
        threadName=name;
    }
    public void run()
    {
        Person person=Person.getInstance();
        Random random =new Random();
        for(int i=0;i<5;i++)
        {
            System.out.println(threadName+":你好,我是【"+couriers[random.nextInt(couriers.length)]+"】有你快递,请尽快来取快递!");
            System.out.println("回答"+threadName+":\t"+person.getAnser());
            try
            {
                this.sleep(1000);
                
            }catch(Exception e)
            {
                System.out.println(e.getMessage());
            }
        }
    }

}
package single;
//饿汉单例模式
public class Person {
    private static Person person=new Person();
    private int num;
    private Person()
    {
        
    }
    public static Person getInstance()
    {
        return person;
    }
    public synchronized String getAnser()
    {
        return "我是XXX,请稍等马上来!这是第"+(++num)+"个快递!";
    }

}



package single;

public class Singleton {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CourierThread courier1=new CourierThread("线程1");
        CourierThread courier2=new CourierThread("线程2");
        courier1.start();
        courier2.start();
    }

}

 

技术分享图片

 

饿汉单例模式实例——取快递

标签:let   package   img   sage   sys   bsp   on()   span   cep   

原文地址:https://www.cnblogs.com/liao-pxsoftware15/p/8975892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!