1、通过使用多线程和普通类,添加sleep,打印时间观察多线程的用法
<?Php
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set("PRC");
ini_set('date.timezone','Asia/Shanghai');
class test extends \Thread {
public function __construct($arg,$time){
$this->arg = $arg;
$this->time = $time;
}
public function run(){
if($this->arg){
sleep($this->time);
printf("%s\n", $this->arg);
print_r(date('Y-m-d H:i:s',time()));
echo '</br>';
}
}
}
class test2{
public function __construct($arg,$time){
$this->arg = $arg;
$this->time = $time;
}
public function show(){
if($this->arg){
sleep($this->time);
printf("%s\n", $this->arg);
print_r(date('Y-m-d H:i:s'));
echo '</br>';
}
}
}
echo "程序开始时间:";
print_r(date('Y-m-d H:i:s',time()));
echo '</br>';
$thread = new test("线程1时间(sleep:3s):",3);
$thread->start();
$thread2 = new test("线程2时间(sleep:1s):",1);
$thread2->start();
$thread3 = new test2("普通类3时间(sleep:5s):",5);
$thread3->show();
$thread4 = new test2("普通类4时间(sleep:5s):",5);
$thread4->show();
echo "程序结束时间:";
print_r(date('Y-m-d H:i:s',time()));
echo '</br>';
?>
下面是运行结果:
由此看出,主进程下面,线程1,线程2 ,普通类3是同时运行的,普通类4是普通类3结束后开始运行的