我正在创建一个简单的计时器,我有一些关于线程的基本知识。 我可以通过等待停止当前正在晒黑的线程,但无法通知它显示“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();
}
}
}
需要帮助。
答案 0 :(得分:1)
public class TimerClass {
Thread t1;
//fileds, initialisation....
public void init() {
//Do Something here...
t1 = new Thread(this);
t1.start();
isAlive = true;
}
public void stopThread() throws InterrupterException {
try {
//Do Something here...
synchronized(t1) {
t1.wait();
}
}catch(InterrupterException e) { e.printStackTrace(); }
}
public void startThread() throws InterrupterException {
try {
//Do Something here...
synchronized(t1) {
t1.notify()
}
}catch(InterrupterException e) { e.printStackTrace(); }
}
}
如果我没有忘记,那应该是这样的