Java創建多線程和線程安全集合Vector
阿新 • • 發佈:2018-07-03
stack 創建線程 rate new t nbsp ash int trac string
public class Test { public static Vector<String> data = new Vector<String>(); public static void main(String[] args) { for (int i = 0; i < 100; i++) { data.add("data" + i); } for (int i = 0; i < 3; i++) { Thread t = newThread() { public void run() { String str = ""; while (data.size() > 0 && !(str = data.remove(0)).equals("")) { System.out.println(this.getId() + "||" + str); //暫停1秒try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }; t.start(); } } }
關於集合安全:
- ArrayList線程不安全,Vector線程安全;
- HashMap線程不安全,HashTable線程安全;
- StringBuilder線程不安全,StringBuffer線程安全。
關於創建線程:
方法一:如上,匿名的線程
方法二:創建一個類MyThread繼承Thread。使用如下:
MyThread t=new MyThread();
t.start();
方法三:創建類MyThread實現接口Runnable。使用如下:
Thread t=new Thread(new MyThread);
t.start();
創建線程可參考:http://www.importnew.com/20672.html
Java創建多線程和線程安全集合Vector