- public class TicketDemo{
- public static void main(String [] args)throws Exception{
-
- System.out.println(Thread.currentThread().getName()+" Begin :");
- Runnable r = new Sale();
-
- Thread t1 = new Thread(r);
- Thread t2 = new Thread(r);
- Thread t3 = new Thread(r);
- Thread t4 = new Thread(r);
- Thread t5 = new Thread(r);
-
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- t5.start();
- }
- }
- /**
- sale类实现runnable接口,把卖票代码写进去,让多个卖票口可以同时执行。
- */
- class Sale implements Runnable{
- private Ticket ticket = Ticket.getInstance();
- public void run(){
- try{
- while (true){
- ticket.sale();
- Thread.sleep(100);
- }
- }
- catch(InterruptedException e){
- throw new RuntimeException("error");
- }
-
- }
- }
- /**
- 单例涉及模式:创建Ticket类
- */
- class Ticket {
- private static Ticket ticket = null;
- private int count = 1000;
- public static Ticket getInstance(){
- if (ticket == null)
- synchronized (Ticket.class){
- if (ticket == null)
- ticket = new Ticket();
- }
- return ticket;
- }
- /*
- 同步方法 里面的代码线程安全,保证卖票不冲突
- */
- public synchronized void sale(){
- if (count > 0)
- System.out.println(Thread.currentThread().getName()+"sale: "+count--);
- else{
- }
- }
- private Ticket(){}
- }
复制代码 |