【发布时间】:2014-04-07 00:32:10
【问题描述】:
我有两个 Java 类
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);
}
}
}
我的第一个问题是:我希望我的第一个线程等到第二个线程完成并且我能够实现这一点,但是在输出中我得到了异常 java.lang.IllegalMonitorStateException。我没有知道为什么。
我的第二个问题是:你能指导我任何可以从基础学习 wait()、notify 和 notifyall() 方法的教程网站吗?
【问题讨论】:
-
你是从阅读
wait()方法的javadoc开始的吗? -
@Sotirios 是的,但我正在寻找一个实用的简单示例。
-
忘记这个例子。了解它的作用。阅读 javadoc 后,您应该知道抛出异常的确切原因。
标签: java multithreading