我正在創建一個簡單的計時器,我有一些關於線程的基本知識。 我可以通過等待來阻止當前sunning線程,但無法通知它顯示「illegalmonitorstateexception」。線程等待睡眠並通知
'import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
/* <applet code = "TimerClass" width = 800 height = 600></applet>*/
public class TimerClass extends Applet implements Runnable, ActionListener
{
Thread t1;
int i;
TextField sec;
Button start;
Button stop;
boolean isStop;
boolean isAlive;
public void init()
{
sec = new TextField(10);
start = new Button("Start");
stop = new Button("Stop");
add(sec);
add(start);
add(stop);
start.addActionListener(this);
stop.addActionListener(this);
isStop = true;
t1 = new Thread(this);
}
public void startThread()
{
t1.start();
isAlive = true;
}
public void awake()
{
try
{
System.out.println(Thread.currentThread().isAlive());
synchronized(t1)
{
Thread.currentThread().notify();
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
//Thread.interrupted();
}
synchronized public void run()
{
do
{
try
{
Thread.sleep(1000);
i += 1;
sec.setText(Integer.toString(i));
System.out.println(i);
if(isStop)
{
break;
}
}
catch(InterruptedException ie)
{
continue;
}
}while(isStop != true);
}
public void stopThread()
{
try
{
synchronized(t1)
{
Thread.currentThread().wait();
}
}
catch(Exception ie)
{
}
}
public void paint(Graphics g)
{
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand() == "Start")
{
if(!isAlive)
{
isStop = false;
System.out.println("Thread start");
startThread();
}
else
{
isStop = false;
System.out.println("Thread start again" + isStop);
awake();
}
}
if(ae.getActionCommand() == "Stop")
{
isStop = true;
stopThread();
}
}
}
需要幫助。
您可以使用wait()方法的同步類。同步(t1) t1.currentThread()。wait(); } –
我嘗試了,問題是在通知我想我只需要通知它重新開始線程,我也檢查線程是活着的,當我通知它,但它不能再等待後再次。 – sank
這個問題每天要問幾次。請谷歌更多或谷歌更好。 – Dariusz