Home  >  Article  >  Backend Development  >  多线程-php单例问题 疑问求解答

多线程-php单例问题 疑问求解答

WBOY
WBOYOriginal
2016-06-02 11:29:511078browse

多线程phpsingleton

A.php

<code><?php class Singleton  {      private static $instance;          private function __construct()      {          echo "This is ok!\r\n";    }      public static function GetInstance()      {          if (!(self::$instance instanceof self))          {              self::$instance = new self();          }          return self::$instance;      }  }  </code></code>

B.php

<code><?phprequire_once ('A.php');class AsyncOperation extends Thread {  public function __construct($arg){    $this->arg = $arg;  }  public function run(){    if($this->arg){      Singleton::GetInstance();    }  }}$arr = array();for($i=0;$istart();}</code>

本人写java的 看到php的单例如A.php表示,但是实际在pthreads扩展下多线程跑的时候,会打印出内容,多次构造该实例。求各位phper解答疑问

对java熟悉点,java中

<code>public class Singleton{    private static Object instance = null;    public Object getInstance(){        if(instance==null){            synchronized(Singleton.class){                if(instance==null){                    instance = new Singleton();                }            }        }        return instance    }}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn