模拟火车票买票案例

 

 

有N张火车票,每张票都有一个编号,同时有10个窗口对外售票,请写一个模拟程序

 

1 用ArrayList实现

 

public class TicketSeller1 {

 

    static List<String> tickets = new ArrayList<>();

 

    static {

        SortedMap s = new TreeMap();

        for (int i = 0; i < 10000 ; i++) {

            tickets.add("票编号: "+i);

        }

    }

 

    public static void main(String[] args) {

        for (int i = 0; i < 10 ; i++) {

            new Thread(()->{

                while (tickets.size()>0){

                  System.out.println("销售了--"+tickets.remove(0));

                }

 

            }).start();

        }

    }

 

}

 

结果:

 

 

2  用Vector实现

 

public class TicketSeller2 {

 

    static Vector<String> tickets = new Vector<>();

 

    static {

        for (int i = 0; i < 1000 ; i++) {

            tickets.add("票编号: "+i);

        }

    }

 

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Thread(()->{

 

                while (tickets.size()>0) {

                    try {

                        TimeUnit.MILLISECONDS.sleep(10);

                    } catch (InterruptedException e) {

                        e.printStackTrace();

                    }

 

                    System.out.println("销售了--" + tickets.remove(0));

                }

            }).start();

        }

    }

 

}

 

结果:

 

3 用synchronized+LinkedList实现

 

public class TicketSeller3 {

 

    static List<String> tickets = new LinkedList<>();

 

    static {

 

        for (int i = 0; i < 1000 ; i++) {

            tickets.add("票编号:"+i);

        }

 

    }

 

    public static void main(String[] args) {

        for (int i = 0; i <10 ; i++) {

            new Thread(()->{

 

                while (true){

 

                    synchronized (tickets){

 

                        if(tickets.size()<=0)break;

 

                        System.out.println("销售了--" + tickets.remove(0));

                    }

 

                }

 

            }).start();

        }

    }

 

}

 

结果:

 

 

4 用ConcurrentLinkedQueue实现

public class TicketSeller4 {

 

    static Queue<String> tickets = new ConcurrentLinkedQueue<>();

 

    static {

        for (int i = 0; i < 1000; i++) {

            tickets.add("票编号:" + i);

        }

    }

 

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {

            new Thread(() -> {

 

                while (true) {

 

                    String s = tickets.poll();

                    if (s == null) break;

                    else System.out.println("销售了:" + s);

 

 

                }

 

            }).start();

        }

    }

}

 

 

总结:

 

1 ArrayList是非线程安全,所以实现不了,会出现多售票的情况

2 Vector虽然是线程安全的,但只在方法上是线程安全的,如下:

 

3 synchronized+LinkedList可以实现,通过加锁来实现同步安全。

4 ConcurrentLinkedQueue可以实现,才有cas +自旋锁实现线程安全。

猜你喜欢

转载自blog.csdn.net/huzhiliayanghao/article/details/106768018
今日推荐