PHP pthreads join方法主要用于等待多線程結(jié)束,以確保多個(gè)線程執(zhí)行完畢之后才繼續(xù)主線程的執(zhí)行。下面簡(jiǎn)單介紹使用
例1:
class MyThread extends Thread {
public function run() {
echo 'Hello World!' . PHP_EOL;
}
}
$thread = new MyThread();
$thread->start();
$thread->join(); // 讓主線程等待該子線程執(zhí)行完畢
echo 'Main Thread' . PHP_EOL;
運(yùn)行以上代碼,會(huì)輸出“Hello World!”和“Main Thread”,這說(shuō)明子線程和主線程是有順序關(guān)系的。
例2:
class MyThread extends Thread {
public function run() {
for ($i = 0; $i < 3; $i++) {
echo 'MyThread:' . $i . PHP_EOL;
usleep(1000);
}
}
}
$threads = [];
for ($i = 0; $i < 3; $i++) {
$threads[$i] = new MyThread();
}
foreach ($threads as $thread) {
$thread->start();
}
foreach ($threads as $thread) {
$thread->join();
}
echo 'Main Thread' . PHP_EOL;
運(yùn)行以上代碼,會(huì)輸出每個(gè)子線程的循環(huán)次數(shù)和“Main Thread”。
例3:
class MyThread extends Thread {
public function run() {
sleep(5);
}
}
$threads = [];
for ($i = 0; $i < 3; $i++) {
$threads[$i] = new MyThread();
}
foreach ($threads as $thread) {
$thread->start();
}
foreach ($threads as $thread) {
$thread->join();
}
echo 'Main Thread' . PHP_EOL;
運(yùn)行以上代碼,會(huì)休眠5秒,然后輸出“Main Thread”。
總結(jié):在使用PHP中的多線程擴(kuò)展時(shí),盡量使用join方法確保多個(gè)線程執(zhí)行完畢之后再繼續(xù)主線程的執(zhí)行。