step1:
import java.util.List;
public class TTThread implements Runnable{
private String link;
public String getLink() {return link;}public void setLink(String link) {this.link = link;}private List<String> info;
public List<String> getInfo() { return info; } public void setInfo(List<String> info) { this.info = info; } public void run() {
// do something; info.add(link); } }
step2:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Main { public static void main(String args[]) throws Exception { long start = System.currentTimeMillis(); List<String> info = Collections.synchronizedList(new ArrayList<String>()); Thread[] threads = new Thread[10];
// ok——1 for (int i = 0; i < 10; ++i) { String val = String.valueOf(i); TTThread r = new TTThread(); r.setLink(val); r.setInfo(info); threads[i] = new Thread(r); threads[i].start(); } // ok——2 for (int i = 0; i < threads.length; ++i) { threads[i].join(); } System.out.println("size: " + info.size()); for (int i = 0; i < info.size(); ++i) { String s = info.get(i); System.out.println(s); } System.out.println("time: " + (System.currentTimeMillis() - start)); } }