脚本宝典收集整理的这篇文章主要介绍了PHP:在线程之间共享静态变量,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
<?PHP class ThreadDemo1 extends Thread { PRivate $mode; //to run 2 threads in different modes private static $test; //Static VARiable shared between threads //Instance is created wITh different mode function __construct($mode) { $this->mode = $mode; } //Set the static variable using mode 'w' function w_mode() { echo 'entered mode w_mode() funcion'; echo "<br />"; //Set shared variable to 0 From initial 100 self::$test = 100; echo "Value of static variable : ".self::$test; echo "<br />"; echo "<br />"; //sleep for a while sleep(1); } //Read the staic vaiable set in mode 'W' function r_mode() { echo 'entered mode r_mode() function'; echo "<br />"; //printing the staic variable set in W mode echo "Value of static variable : ".self::$test; echo "<br />"; echo "<br />"; //Sleep for a while sleep(2); } //Start the thread in different modes public function run() { //Print the mode for reference echo "Mode in run() method: ".$this->mode; echo "<br />"; switch ($this->mode) { case 'W': $this->w_mode(); break; case 'R': $this->r_mode(); break; default: echo "Invalid option"; } } } $trd1 = new ThreadDemo1('W'); $trd2 = new ThreadDemo1('R'); $trd3 = new ThreadDemo1('R'); $trd1->start(); $trd2->start(); $trd3->start(); ?>
预期产量是,
run()方法中的模式:W
进入模式w_mode()函数
静态变量的值:100
run()方法中的模式:R
进入模式r_mode()函数
静态变量的值:100
run()方法中的模式:R
进入模式r_mode()函数
静态变量的值:100
但实际上我得到的输出为,
run()方法中的模式:W
进入模式w_mode()函数
静态变量的值:100
run()方法中的模式:R
进入模式r_mode()函数
静态变量的值:
run()方法中的模式:R
进入模式r_mode()函数
静态变量的值:
….真的没有意识到原因.请帮忙.
以上是脚本宝典为你收集整理的PHP:在线程之间共享静态变量全部内容,希望文章能够帮你解决PHP:在线程之间共享静态变量所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。