2015-10-04 53 views
0

创建Fibonacci序列我的notifyAll()有什么问题?

public void run(){ 
     int a=0,b=1,c; 
     while(a<=10000){ 
      prim chk= new prim(a); 
      chk.start(); 
      synchronized (chk) { 
       try { 
        sleep(200); 
        chk.wait(); 
       } catch (InterruptedException e) { 
        return; 
       } 
      } 
      c=a+b; 
      a=b; 
      b=c; 
     } 
    } 

来检查我已经创建另一个线程素数(只是为了练习)

 public void run(){ 
      synchronized (this) { 
       int fl=1; 
       if(a==1||a==2) 
        fl=0; 
       else 
        for(int i=2;i<=Math.sqrt(a);i++) 
         if(a%i==0) 
          fl=0; 
       if(fl==0) 
        System.out.println(a); 
      } 
      notifyAll(); 
     } 

有输出许多IllegalMonitorState例外。

+1

你不能从同步块外部调用'notifyAll();' –

+1

要通知其他线程在某个监视器上观察(等待)你的线程需要拥有它。所以你需要在'synchronize(this)'块内调用'this.notifyAll'。 – Pshemo

+0

这已被问过很多次,例如,请看这[重复问题](http://stackoverflow.com/questions/13335367/why-does-this-code-result-in-illegalmonitorstate-exception)这是用于关闭您的问题。对于更多类似的问题/答案,请查看此[本站搜索](http://stackoverflow.com/search?q=%5Bjava%5D+IllegalMonitorStateException+notifyall)。事实上,第二个链接是最重要的,因为它会向您介绍本网站的搜索功能,并帮助减少不必要的重复问题。 –

回答