在Java中,處理列表的并發操作需要使用線程安全的數據結構。Java提供了幾種線程安全的數據結構,如Vector
、Collections.synchronizedList()
方法包裝的列表以及ConcurrentHashMap.newKeySet()
方法返回的集合。下面是一些示例:
import java.util.Vector;
public class ConcurrentListExample {
public static void main(String[] args) {
Vector<String> list = new Vector<>();
// 創建兩個線程,分別向列表中添加元素
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
list.add("Thread1-" + i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
list.add("Thread2-" + i);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Vector: " + list);
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ConcurrentListExample {
public static void main(String[] args) {
List<String> list = Collections.synchronizedList(new ArrayList<>());
// 創建兩個線程,分別向列表中添加元素
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
list.add("Thread1-" + i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
list.add("Thread2-" + i);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Synchronized List: " + list);
}
}
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentListExample {
public static void main(String[] args) {
Set<String> set = ConcurrentHashMap.newKeySet();
// 創建兩個線程,分別向集合中添加元素
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
set.add("Thread1-" + i);
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
set.add("Thread2-" + i);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ConcurrentHashMap KeySet: " + set);
}
}
注意:在使用Collections.synchronizedList()
包裝列表時,需要注意對整個操作進行同步,以避免并發問題。例如,在上面的示例中,我們使用了join()
方法來等待兩個線程完成操作。而在使用ConcurrentHashMap.newKeySet()
時,由于它本身是線程安全的,因此不需要額外的同步措施。