1 <?php 2 class vote extends Thread { 3 public $res = ''; 4 public $url = array(); 5 public $name = ''; 6 public $runing = false; 7 public $lc = false; 8 public function __construct($name) { 9 $this->res = '暫無,第一次運行.'; 10 $this->param = 0; 11 $this->lurl = 0; 12 $this->name = $name; 13 $this->runing = true; 14 $this->lc = false; 15 } 16 public function run() { 17 while ($this->runing) { 18 if ($this->param != 0) { 19 $nt = rand(1, 10); 20 echo "線程[{$this->name}]收到任務參數::{$this->param},需要{$nt}秒處理數據.\n"; 21 $this->res = rand(100, 999); 22 sleep($nt); 23 $this->lurl = $this->param; 24 $this->param = ''; 25 } else { 26 echo "線程[{$this->name}]等待任務..\n"; 27 } 28 sleep(1); 29 } 30 } 31 } 32 //這里創建線程池. 33 $pool[] = new vote('a'); 34 $pool[] = new vote('b'); 35 $pool[] = new vote('c'); 36 //啟動所有線程,使其處於工作狀態 37 foreach ($pool as $w) { 38 $w->start(); 39 } 40 //派發任務給線程 41 for ($i = 1; $i < 10; $i++) { 42 $worker_content = rand(10, 99); 43 while (true) { 44 foreach ($pool as $worker) { 45 //參數為空則說明線程空閑 46 if ($worker->param=='') { 47 $worker->param = $worker_content; 48 echo "[{$worker->name}]線程空閑,放入參數{$worker_content},上次參數[{$worker->lurl}]結果[{$worker->res}].\n"; 49 break 2; 50 } 51 } 52 sleep(1); 53 } 54 } 55 echo "所有線程派發完畢,等待執行完成.\n"; 56 //等待所有線程運行結束 57 while (count($pool)) { 58 //遍歷檢查線程組運行結束 59 foreach ($pool as $key => $threads) { 60 if ($worker->param=='') { 61 echo "[{$threads->name}]線程空閑,上次參數[{$threads->lurl}]結果[{$threads->res}].\n"; 62 echo "[{$threads->name}]線程運行完成,退出.\n"; 63 //設置結束標志 64 $threads->runing = false; 65 unset($pool[$key]); 66 } 67 } 68 echo "等待中...\n"; 69 sleep(1); 70 } 71 echo "所有線程執行完畢.\n";