一、簡單線程同步問題 ...
一、簡單線程同步問題
package com.ietree.multithread.sync; import java.util.Vector; public class Tickets { public static void main(String[] args) { // 初始化火車票池並添加火車票:避免線程同步可採用Vector替代ArrayList HashTable替代HashMap final Vector<String> tickets = new Vector<String>(); // Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>()); for (int i = 1; i <= 1000; i++) { tickets.add("火車票" + i); } // for (Iterator iterator = tickets.iterator(); iterator.hasNext();) { // String string = (String) iterator.next(); // tickets.remove(20); // } for (int i = 1; i <= 10; i++) { new Thread("線程" + i) { public void run() { while (true) { if (tickets.isEmpty()) { break; } System.out.println(Thread.currentThread().getName() + "---" + tickets.remove(0)); } } }.start(); } } }