IllegalMonitorStateException on wait() call

后端 未结 10 1501
感动是毒
感动是毒 2020-11-22 11:37

I am using multi-threading in java for my program. I have run thread successfully but when I am using Thread.wait(), it is throwing java.lang.IllegalMonit

10条回答
  •  忘掉有多难
    2020-11-22 11:48

    Those who are using Java 7.0 or below version can refer the code which I used here and it works.

    public class WaitTest {
    
        private final Lock lock = new ReentrantLock();
        private final Condition condition = lock.newCondition();
    
        public void waitHere(long waitTime) {
            System.out.println("wait started...");
            lock.lock();
            try {
                condition.await(waitTime, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            lock.unlock();
            System.out.println("wait ends here...");
        }
    
        public static void main(String[] args) {
            //Your Code
            new WaitTest().waitHere(10);
            //Your Code
        }
    
    }
    

提交回复
热议问题