有100张票
四个售票窗口
一个售票的代表一个线程帮我写下  谢谢

解决方案 »

  1.   

    思路:用一个ExcutorServer启动100个线程,在线程的run方法中对一个线程安全的集合进行读写操作
      

  2.   

    ExcutorServer es=Executors.newCachedThreadPool();
    for(int i=0;i<100;i++)
    es.execute(new Tread());run方法里用一个线程安全的集合去存储那些票,就可以保证同步
    如List list = Collections.synchronizedList(new ArrayList());
      

  3.   


    public class TestThread extends Thread { private static int tickets = 400;
    private String name;
    private int selled; public TestThread(String name) {
    this.name = name;
    } public void run() {
    while (tickets > 0) {
    tickets--;
    selled++;
    System.out.println(name + "售出了" + selled + "张票, 还剩" + tickets
    + "张票。");
    try {
    this.currentThread().sleep(500);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    } public static void main(String[] args) {
    for (int i = 0; i < 4; i++) {
    new TestThread("售票窗口" + i).start();
    }
    }}