我定义了一个类
public class Stopwatch1 extends JPanel implements Runnable {
public void paintComponent( Graphics g ){
} public void run(){
repaint();
}}
在调用的时候是用如下方法:
public class ShowTimeTest extends JFrame {
Stopwatch1 myPanel=new Stopwatch1();
thread1 = new Thread(myPanel);
thread1.start();}
原来是用thread1.suspend()和thread1.resume() 来控制线程的,现在我想用继承Object类的wait()和notify()来控制。所以我在Stopwatch1类的 run()方法中,利用控制语句来实现wait(),代码如下public class Stopwatch1 extends JPanel implements Runnable {
int control=0 ;
final int STOP=1; public void paintComponent( Graphics g ){
} public void run(){
if(control==STOP) stopThread(); //做判断,当control被修改后 调用stopThread()方法
repaint();
} public void stopThread(){
control=0; //目的还原control,以便下次启动时不调用该方法
try{wait();}catch(InterruptedException e){}
}
public void setControl(){ //让实例话后的对象通过该方法,去停止该线程
control=1;
}
}
现在我的问题是:怎么才能通过notify()再次启动该线程,在那里使用该方法?
(给我点思路也行)
public class Stopwatch1 extends JPanel implements Runnable {
public void paintComponent( Graphics g ){
} public void run(){
repaint();
}}
在调用的时候是用如下方法:
public class ShowTimeTest extends JFrame {
Stopwatch1 myPanel=new Stopwatch1();
thread1 = new Thread(myPanel);
thread1.start();}
原来是用thread1.suspend()和thread1.resume() 来控制线程的,现在我想用继承Object类的wait()和notify()来控制。所以我在Stopwatch1类的 run()方法中,利用控制语句来实现wait(),代码如下public class Stopwatch1 extends JPanel implements Runnable {
int control=0 ;
final int STOP=1; public void paintComponent( Graphics g ){
} public void run(){
if(control==STOP) stopThread(); //做判断,当control被修改后 调用stopThread()方法
repaint();
} public void stopThread(){
control=0; //目的还原control,以便下次启动时不调用该方法
try{wait();}catch(InterruptedException e){}
}
public void setControl(){ //让实例话后的对象通过该方法,去停止该线程
control=1;
}
}
现在我的问题是:怎么才能通过notify()再次启动该线程,在那里使用该方法?
(给我点思路也行)
不好意思 是我写错了,我的目的就是想唤醒被缩住的线程。
不然会有异常
不过 还是唤醒不了,是我哪里出错了嘛?
我是想放在监听器里来唤醒的,代码如下:
continueButton.addActionListener( new ActionListener() { // anonymous inner class
public void actionPerformed( ActionEvent event ) {
//returnThread().resume();
synchronized (this){notifyAll();}
} } // end anonymous inner class );
这记几天在学线程,
我就是在做一个秒表记时器,用线程来控制它,
synchronized 的关键字 起到的作用 是让一个线程来访问,那其他线程同时使用的时候会在此处阻塞嘛?