我有兩個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後,您應該確切知道拋出異常的原因。 –