慕標5832272
TA貢獻1966條經驗 獲得超4個贊
以下是兩個線程:
import java.util.*;
public class Thread_List_Operation {
//假設有這么一個隊列
static List list = new LinkedList();
public static void main(String[] args) {
Thread t;
t = new Thread(new T1());
t.start();
t = new Thread(new T2());
t.start();
}
}
//線程T1,用來給list添加新元素
class T1 implements Runnable{
void getElemt(Object o){
Thread_List_Operation.list.add(o);
System.out.println(Thread.currentThread().getName() + "為隊列添加了一個元素");
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
getElemt(new Integer(1));
}
}
}
//線程T2,用來給list添加新元素
class T2 implements Runnable{
void getElemt(Object o){
Thread_List_Operation.list.add(o);
System.out.println(Thread.currentThread().getName() + "為隊列添加了一個元素");
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
getElemt(new Integer(1));
}
}
}
//結果(亂序)
Thread-0為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-1為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
Thread-0為隊列添加了一個元素
查看完整回答