安装教程请参考thread安装
直接上一段简单的代码
<code><span><?php </span><span><span>class</span><span>test</span><span>extends</span><span>Thread</span> {</span><span>public</span><span><span>function</span><span>__construct</span><span>(<span>$fun</span>)</span> {</span><span>$this</span>->fun=<span>$fun</span>; } <span>public</span><span><span>function</span><span>run</span><span>()</span> {</span><span>$param</span>=<span>$this</span>->fun; <span>$this</span>-><span>$param</span>(); } <span>private</span><span><span>function</span><span>test1</span><span>()</span> {</span><span>echo</span><span>1</span>; <span>echo</span><span>"<br>"</span>; } <span>private</span><span><span>function</span><span>test2</span><span>()</span> {</span> sleep(<span>3</span>); <span>echo</span><span>2</span>; <span>echo</span><span>"<br>"</span>; } <span>private</span><span><span>function</span><span>test3</span><span>()</span> {</span><span>echo</span><span>3</span>; <span>echo</span><span>"<br>"</span>; } } <span>$arr</span>=<span>array</span>(<span>'test1'</span>,<span>'test2'</span>,<span>'test3'</span>); <span>foreach</span> (<span>$arr</span><span>as</span><span>$fun</span>) { <span>$th</span>[]=<span>new</span> test(<span>$fun</span>); } <span>foreach</span> (<span>$th</span><span>as</span><span>$worker</span>) { <span>$worker</span>->start(); } </span></code>
输出结果是
1
3
2
test 类继承thread类,需要实现run方法,start方法会自动开启一个线程来执行run方法里的程序,thread具体的方法请参考官方手册
http://php.net/manual/zh/class.thread.php
以上就介绍了php thread扩展的使用,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。