Vector 線程安全,也可能出現髒數據


public static class MyThread extends Thread{
	private Vector<String> container = null;
	
	public MyThread(Vector<String> container) {
		this.container = container;
	}

	@Override
	public void run() {
		while (true) {
			try {
				if(container.size()<1){
					Thread.sleep(500);
					container.add("index: "+container.size());
				}else{
					break;
				}
			} catch (InterruptedException e) {
			}
		}
	}
}

public static void main(String[] args) throws InterruptedException {
	Vector<String> list = new Vector<String>();
	new MyThread(list).start();
	new MyThread(list).start();
	Thread.sleep(2000);
	System.out.println(list.size());
}
結果: 2
相關文章
相關標籤/搜索