餓漢單例模式實例——取快遞

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();
    }

}
 
 

 

相關文章
相關標籤/搜索