2013-03-20 60 views
0

当过我打电话pauseThread()它总是抛出抛出:IllegalMonitorStateException。大众抛出:IllegalMonitorStateException上线等待

我注意到,我需要自己的对象监视器能够导致线程等待的文件中。

与这段代码

synchronized (obj) { 
     while (<condition does not hold>) 
      obj.wait(); 
     ... // Perform action appropriate to condition 
    } 

在这种情况下将在OBJ PARAM是转轮 的同时(ServerTickHandler.peakBlockDestructionQueue()== NULL){} 但当obj.wait();被称为是否需要通知?或将它通知本身时,同时条件不为真 将同步(){}码块连续地循环或将它仍然需要内的while循环的同步(){}做到这一点?

编辑:将在syncronized(){}通过run方法里面去?

这里是我的

public class ServerTickSaveHandler implements Runnable 
{ 
    private static Thread runner; 
    /** 
    * Creates a new thread for dealing with logging block destruction when using certain tools. 
    * @param threadName Name of the thread. 
    */ 
    public ServerTickSaveHandler(String threadName) 
    { 
     runner = new Thread(this, threadName); 
    } 
    /** 
    * If thread has nothing to do we shall pause it so it does not needlessly run :D. 
    * @throws InterruptedException 
    */ 
    public void pauseThread() 
    { 
     try 
     { 
      runner.wait(); 
     } 
     catch (InterruptedException e) 
     { 
      e.printStackTrace(); 
     } 
     catch(IllegalMonitorStateException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
    /** 
    * If Items from DropItemQueue need ticking lets resume this thread. 
    * @throws IllegalMonitorStateException 
    */ 
    public void resumeThread() 
    { 
     try 
     { 
      runner.notify(); 
     } 
     catch (IllegalMonitorStateException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
    /** 
    * The thread that is spawned when this object is created. 
    */ 
    public void run() 
    { 
     while (true) 
     { 
      // long start = System.currentTimeMillis(); 

      WorldData worldData = ServerTickHandler.getBlockDestructionQueue(); 
      if (worldData != null) 
      { 
       worldData.saveToFile(); 
      } 
      else pauseThread(); 

      // long end = System.currentTimeMillis(); 

      // NumberFormat formatter = new DecimalFormat("#0.00000"); 
      // Utils.log("Save Tick Handler Execution time is " + 
      // formatter.format((end - start)/1000d) + " seconds"); 
     } 
    } 
    /** 
    * Starts the thread. 
    * @throws IllegalStateException 
    */ 
    public void startThread() 
    { 
     try 
     { 
      runner.start(); 
     } 
     catch (IllegalStateException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

回答

2

类如记录,你一定要挺住,你叫wait()/notify()对象的监视器。由于您在runner上调用这些方法,因此这些说明必须位于

synchronized(runner) { 

块中。

也就是说,在线程上调用wait()/notify()是一个很奇怪的选择。你最好使用最后的专用锁对象来等待/通知。你的程序还有其他不好的选择。例如,从构造函数初始化静态字段。

wait()notify()非常低的水平,很难使用原语。您应该使用像Locks,Semaphores,CountDownLatches,BlockingQueues等更高级别的抽象。

+0

谢谢你,它现在的工作。 – JohnM 2013-03-20 23:34:22

相关问题