我有两个Java类无法在线程中运行wait()方法?
public class Firstclass
{
public static void main(String args[]) throws InterruptedException
{
System.out.println("Main start....");
Secondclass s=new Secondclass();
Thread t1 = new Thread(s);
t1.setName("First Thread");
Thread t2=new Thread(s);
t2.setName("Second Thread");
t1.start();
t2.start();
System.out.println("Main close...");
}
}
和
public class Secondclass implements Runnable
{
public static Object obj;
int counter=10;
public void inc()
{
counter++;
}
public void dec()
{
counter--;
}
@Override
public void run()
{
try
{
loop();
}
catch(Exception e)
{
System.out.println("exception is"+e);
}
}
public void loop() throws InterruptedException
{
for(int i=0;i<10;i++)
{
if(Thread.currentThread().getName().equals("First Thread"))
{
Thread.currentThread().wait();
inc();
}
else
{
dec();
}
System.out.println("Counter=="+counter);
}
}
}
我的第一个问题是:我想我的第一个线程等待,直到第二个线程完成,我能够acheive这一点,但在输出我得到例外java.lang.IllegalMonitorStateException
。我不知道为什么。
我的第二个问题是:你能指导我任何教程网站,我可以从基础学习等待(),通知和notifyall()方法。
你是否已经开始阅读'wait()'方法的javadoc? –
@ Sotirios是的,但我一直在寻找一个实用的简单例子。 – TruePS
忘掉这个例子。了解它的作用。读完javadoc后,您应该确切知道抛出异常的原因。 –