Thread.join()
方法用于等待線程執(zhí)行完畢。在 Java 中,可以在需要等待某個(gè)線程執(zhí)行完畢后再執(zhí)行后續(xù)代碼的場(chǎng)景中使用 Thread.join()
。而并發(fā)集合類(如 ConcurrentHashMap
、CopyOnWriteArrayList
等)是 Java 提供的一組線程安全的集合類,它們可以在多線程環(huán)境下安全地使用。
Thread.join()
方法的使用場(chǎng)景通常與線程同步和協(xié)作有關(guān)。如果你需要在某個(gè)線程執(zhí)行完畢后再執(zhí)行后續(xù)代碼,并且這個(gè)后續(xù)代碼需要訪問并發(fā)集合類,那么可以在訪問并發(fā)集合類之前調(diào)用 Thread.join()
方法。
以下是一個(gè)簡(jiǎn)單的示例,展示了如何在多線程環(huán)境下使用 Thread.join()
和并發(fā)集合類:
import java.util.concurrent.ConcurrentHashMap;
public class JoinExample {
public static void main(String[] args) {
ConcurrentHashMap<String, String> concurrentMap = new ConcurrentHashMap<>();
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 started");
try {
// 模擬耗時(shí)操作
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 finished");
// 在 Thread 1 執(zhí)行完畢后,向并發(fā)集合類中添加元素
concurrentMap.put("key1", "value1");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread 2 started");
try {
// 模擬耗時(shí)操作
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 finished");
});
thread2.start();
try {
// 等待 Thread 2 執(zhí)行完畢
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread1.start();
try {
// 等待 Thread 1 執(zhí)行完畢
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 輸出并發(fā)集合類的元素
concurrentMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
}
}
在這個(gè)示例中,我們創(chuàng)建了兩個(gè)線程 thread1
和 thread2
。thread2
首先啟動(dòng)并執(zhí)行完畢,然后 thread1
啟動(dòng)。在 thread2
執(zhí)行完畢后,我們向 concurrentMap
中添加了一個(gè)元素。接著,在 thread1
執(zhí)行完畢后,我們輸出了 concurrentMap
中的所有元素。通過使用 Thread.join()
方法,我們確保了在訪問并發(fā)集合類之前,線程已經(jīng)執(zhí)行完畢。