java.lang.IllegalMonitorStateException错误的解决

出现java.lang.IllegalMonitorStateException错误,由以下情况导致:
1>当前线程不含有当前对象的锁资源的时候,调用obj.wait()方法;
2>当前线程不含有当前对象的锁资源的时候,调用obj.notify()方法。
3>当前线程不含有当前对象的锁资源的时候,调用obj.notifyAll()方法。
例子:
 
  
public class ThreadTest {
	
	class ThreadTest1 extends Thread{
		String a;
		public ThreadTest1(String a){
			this.a=a;
		}

		public void run(){
			try {
				a.wait();
			} catch (InterruptedException e) {

			}
		}
	}

	public static void main(String[] args){
		String a="11";
		ThreadTest test = new ThreadTest();
		ThreadTest1 test1 = test.new ThreadTest1(a);
		test1.start();
	}

}
以上程序运行后会出现错误:
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
	at java.lang.Object.wait(Native Method)
	at java.lang.Object.wait(Object.java:485)
	at ThreadTest$ThreadTest1.run(ThreadTest.java:11)
解决办法:
public class ThreadTest {
	
	class ThreadTest1 extends Thread{
		String a;
		public ThreadTest1(String a){
			this.a=a;
		}

		public void run(){
			try {
				synchronized (a) {//在执行a.wait()前,先让当前线程获取a的锁
					a.wait();
}} catch (InterruptedException e) {}}}public static void main(String[] args){String a="11";ThreadTest test = new ThreadTest();ThreadTest1 test1 = test.new ThreadTest1(a);test1.start();}}
 修改后便可以顺利运行 
  
 
 

你可能感兴趣的:(java异常处理)