执行以下代码并抛出IllegalMonitorStateException
异常后。我收到错误消息:
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at com.blt.ThreadExample.main(ThreadExample.java:21)
我是多线程的新手,我想在代码中使用wait()
和notify()
。
package com.blt;
public class ThreadExample implements Runnable {
public static void main(String args[])
{
System.out.println("A");
Thread T = new Thread(new ThreadExample());
Thread T1 = new Thread(new ThreadExample());
System.out.println("B");
try
{
T.setName("thread 1");
T.start();
T1.setName("thread 2");
System.out.println("C");
T.notify();
System.out.println("D");
T1.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void run()
{
synchronized(ThreadExample.class)
{
for(int i=0; i<5; i++)
{
try
{
Thread.currentThread().wait(400);
System.out.println("Inside run=>"+Thread.currentThread().getName());
Thread.currentThread().sleep(2000);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}