【发布时间】:2012-01-31 20:54:42
【问题描述】:
我已经让两个线程与 Netbeans 一起运行,我想添加三个按钮来停止-暂停-继续它们。它们突出显示和取消突出显示文本。其中一个的代码是
class TimeHighspell extends Thread{
int x=0;
int pos;
int delay;
Control control ;
String [] result;
int[] anArray;
public TimeHighspell (Control c, int delay,String [] result1,int pos,int[] anArray) {
x=0;
control = c;
this.delay = delay;
result=result1;
this.pos=pos;
this.anArray=anArray;
}
public void run(){
while (true) {
control.putHighspell(result,pos,x);
int Search=x+1;
Arrays.sort(anArray);
int index = Arrays.binarySearch(anArray,Search);
if (index > 0)
pos=pos+result[x].length()+1;
else
pos=pos+result[x].length();
x=x+1;
try {
Thread.sleep( delay );
}
catch ( InterruptedException e ) {}
}}}
class Control {
private boolean ping = false;
public synchronized void putHigh(String [] result,int pos,int x){
while(ping==false)
try{
//notify();
wait();
}catch( InterruptedException e){}
highlight(editPane, result[x],pos);
HighBold(editPane,result[x],pos);
ping = false;
notifyAll();
}
要启动它们,我使用一个按钮来放置此代码
private void HighWordActionPerformed(java.awt.event.ActionEvent evt) {
String [] result1 = editPane.getText().split("\\s");
Control c = new Control();
int delay;
int pos=0;
delay=Slider.getValue();
RemoveHigh p1 = new RemoveHigh(c, delay);
TimeHigh c1 = new TimeHigh(c, delay,result1,pos);
p1.start();
c1.start();}
【问题讨论】:
-
按钮的 GUI 代码在哪里?
-
只需使用两个可变布尔字段:
stop和pause,并在while (true)块的开头检查它们。 -
我只放了剩下的代码
-
所以我在while循环中放了一个if,如果我想让线程停止代码前按钮将是stop==true??
-
catch( InterruptedException e){}... 叹息 ...
标签: java multithreading wait