Heim  >  Artikel  >  Backend-Entwicklung  >  多线程-php单例问题 疑问求解答

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

WBOY
WBOYOriginal
2016-06-02 11:29:511076Durchsuche

多线程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>
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn