[英]How do I invoke wait() method in main method? if I use it then it will give java.lang.IllegalMonitorStateException
I get an error : 我得到一个错误:
package main_test;
public class Main {
public static void main(String[] args) throws InterruptedException
{
Main m = new Main();
System.out.println("Main Started");
m.wait();
System.out.println("Main Terminated");
}
}
You have to acquire the lock first, before you can call wait. 您必须先获取锁,然后才能致电等待。 Try something like this: 尝试这样的事情:
public static void main(String[] args) throws InterruptedException {
Main m = new Main();
System.out.println("Main Started");
synchronized (m) {
m.wait();
}
System.out.println("Main Terminated");
}
But now the program will not terminate - obviously. 但是现在程序不会终止-显然。 Some other thread needs to call notify()
on the object you called wait()
. 其他一些线程需要在您调用了wait()
的对象上调用notify()
wait()
。 (This is why its a bad idea to use a local variable but this is just an example so...) (这就是为什么使用局部变量是个坏主意,但这只是一个例子,所以...)
See the java tutorial for more information. 有关更多信息,请参见Java教程 。
public static void main(String[] args) throws InterruptedException {
Main m = new Main();
System.out.println("Main Started");
synchronized (m) {
m.wait();
}
System.out.println("Main Terminated");
}
Program wont terminate!! 程序不会终止!
You have to explicitly acquire monitor by making particular block or method synchronized. 您必须通过使特定的块或方法同步来显式获取监视器。 wait() releases lock held by executing thread and notify() informs other thread for execution. wait()释放执行线程持有的锁,notify()通知其他线程执行。
Example: 例:
Object lock= new Object();
synchronized(lock){
// write your code here. You may use wait() or notify() as per your requirement.
wait(1000);
notify();
}
Alternatively you may use synchronized method: 或者,您可以使用同步方法:
public synchronized void putMessage(){
// write your code
wait(1000);
notify();
// write your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.