在Java中,Thread.join()
方法用于等待一個線程執(zhí)行完畢后再繼續(xù)執(zhí)行當(dāng)前線程。以下是一些常見的并發(fā)編程模式,這些模式中可能會使用到Thread.join()
來實(shí)現(xiàn)線程間的協(xié)作:
Thread t1 = new Thread(new Runnable() {
public void run() {
// 任務(wù)1
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
try {
t1.join(); // 等待t1線程完成
} catch (InterruptedException e) {
e.printStackTrace();
}
// 任務(wù)2
}
});
t1.start();
t2.start();
Thread.join()
可以用于等待某個線程完成,以便在該線程完成后執(zhí)行其他操作。例如:Thread t1 = new Thread(new Runnable() {
public void run() {
// 任務(wù)1
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
// 任務(wù)2
}
});
t1.start();
t2.start();
try {
t1.join(); // 等待t1線程完成
} catch (InterruptedException e) {
e.printStackTrace();
}
// 在這里執(zhí)行依賴于t1的任務(wù)
Thread.join()
可以用于等待線程池中的某個線程完成。例如:ExecutorService executor = Executors.newFixedThreadPool(2);
Future<?> future1 = executor.submit(new Runnable() {
public void run() {
// 任務(wù)1
}
});
Future<?> future2 = executor.submit(new Runnable() {
public void run() {
// 任務(wù)2
}
});
try {
future1.get(); // 等待future1對應(yīng)的線程完成
future2.get(); // 等待future2對應(yīng)的線程完成
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
Thread.join()
可以用于確保數(shù)據(jù)在生產(chǎn)者和消費(fèi)者之間正確地傳遞和處理。例如:BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Thread producer = new Thread(new Runnable() {
public void run() {
try {
for (int i = 0; i < 10; i++) {
queue.put(i); // 生產(chǎn)數(shù)據(jù)
Thread.sleep(100); // 模擬生產(chǎn)延遲
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(new Runnable() {
public void run() {
try {
while (true) {
Integer item = queue.take(); // 消費(fèi)數(shù)據(jù)
System.out.println("Consumed: " + item);
Thread.sleep(200); // 模擬消費(fèi)延遲
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
producer.join(); // 等待生產(chǎn)者線程完成
這些模式只是Java并發(fā)編程中的一部分,實(shí)際上還有更多的模式和組合方式可以使用Thread.join()
來實(shí)現(xiàn)線程間的協(xié)作。