线程问题<3>

来源:互联网 发布:手机网络无法登陆钉钉 编辑:程序博客网 时间:2024/06/10 04:10

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

1.使用锁

缺点: 效率不高

public class Test7 {private LinkedList list = new LinkedList();public static void main(String[] args) {final Test7 t = new Test7();for (int i = 0; i < 3000; i++) {t.list.add(i);}for (int i = 0; i < 10; i++) {new Thread() {public void run() {synchronized (t.list) {while(t.list.size()>0) {System.out.println("销售了" + t.list.removeFirst());}}}}.start();}}}

2.使用并发容器: ConcurrentLinkedQueue

public class Test8 {static Queue<String> tickets = new ConcurrentLinkedQueue<String>();static {for (int i = 0; i < 5000; i++) {tickets.add("票编号" + i);}}public static void main(String[] args) {for (int i = 0; i < 10; i++) {new Thread() {public void run() {while(true) {String s = tickets.poll();if(s == null) break;else System.out.println("销售了" + s);}}}.start();}}}


原创粉丝点击