有些时候我们不希望线程调用start()后就立刻执行,在处理完我们的业务逻辑后在需要的时候让线程执行。
<?php
class Sync extends Thread {
    private $name = '';

    public function __construct($name) {
        $this->name = $name;
    }

    public function run() {
        //让线程进入等待状态
        $this->synchronized(function($self){
            $self->wait();
        }, $this);

        echo "thread {$this->name} run... \r\n";
    }
}

//我们创建10个线程
$threads = array();
for($ix = 0; $ix < 10; ++$ix) {
    $thread = new Sync($ix);
    $thread->start();
    $threads[] = $thread;
}

$num = 1;
while(true) {
    if($num > 5) {
        //当$num大于5时,我们才唤醒线程让它们执行
        foreach($threads as $thread) {
            $thread->synchronized(function($self){
                $self->notify();
            }, $thread);
        }
        break;
    }

    //这里我们处理我们需要的代码
    //这时候线程是处在等待状态的
    echo "wait... \r\n";
    sleep(3);
    ++$num;
}

foreach($threads as $thread) {
    $thread->join();
}
echo "end... \r\n";
10个线程在start后并没有立刻执行,而是等待中,直到通过notify()发送唤醒通知,线程才执行。
posted on 2017-01-17 20:07  怀素真  阅读(625)  评论(0编辑  收藏  举报