##知識點git
class myQueue extends Threaded { public function __construct($size){ $this->atomic = 0; $this->minSize = 0; $this->maxSize = $size; $this->Queue = new Threaded(); } public function put($item) { $this->synchronized(function($thread,$item){ while ($thread->Queue->count() == $thread->maxSize) { print "wait.."."\r\n"; $this->wait(); } $thread->Queue[] = $item; print "[#myQueueArray] <"."添加元素".$item."\r\n"; $thread->increment(); $thread->notify(); }, $this,$item); } public function tack() { $item = null; $this->synchronized(function($thread,$item){ while ($thread->Queue->count() == $thread->minSize) { print "wait.."."\r\n"; $this->wait(); } $item = $thread->Queue->shift(); print "[#myQueueArray] >"."移除元素".$item."\r\n"; $thread->decrement(); $thread->notify(); }, $this,$item); return $item; } public function increment() { $this->automic += 1; } public function decrement() { $this->automic -= 1;} public function run(){ /* this particular object won't run */ } } $myQueue = new myQueue(5); $myQueue->put('a'); $myQueue->put('b'); $myQueue->put('c'); $myQueue->put('d'); $myQueue->put('e'); $name = 't1'; $t1 = new class($myQueue,$name) extends Thread { public function __construct(Threaded $myQueue,$name) { $this->name = $name; $this->myQueue = $myQueue; } public function run() { $this->myQueue->put('f'); $this->myQueue->put('g'); } }; $t1->start(); $name = 't2'; $t2 = new class($myQueue,$name) extends Thread { public function __construct(Threaded $myQueue,$name) { $this->name = $name; $this->myQueue = $myQueue; } public function run() { $this->myQueue->tack(); $this->myQueue->tack(); } }; $t2->start();
###運行結果github