当使用两个线程时,如何确保打印顺序与原始数组中的顺序相同?我希望它打印“0 1 2 3 4 5 6 7 8 9”,但目前不能保证订单。有什么办法让它井井有条吗?十分感谢。
public class Test {
public static void main(String[] args){
DataStore dataStore = new DataStore();
for(int i=0; i<10; i++){
dataStore.add(String.valueOf(i));
}
CopyThread t1 = new CopyThread(dataStore);
CopyThread t2 = new CopyThread(dataStore);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch(Throwable t) {
}
}
}
class CopyThread extends Thread {
private DataStore data;
public CopyThread(DataStore data){
this.data = data;
}
public void run(){
DataStore.Line line = null;
int lineID;
while( (line = data.getLine()) != null ){
lineID = line.id;
System.out.println(Thread.currentThread().getName() + ": " + lineID);
}
}
}
class DataStore {
ArrayList<String> lines = new ArrayList<String>();
int current = 0;
public synchronized Line getLine () {
if (current >= lines.size()) {
return null;
}
Line line = new Line(lines.get(current), current);
current++;
return line;
}
public synchronized void add (String s) {
lines.add(s);
}
public synchronized int size () {
return lines.size();
}
public static class Line {
public String line;
public int id;
public Line (String str, int i) {
line = str;
id = i;
}
}
}