【问题标题】:stop-pause-continue two synchronized threads停止-暂停-继续两个同步线程
【发布时间】: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 代码在哪里?
  • 只需使用两个可变布尔字段:stoppause,并在 while (true) 块的开头检查它们。
  • 我只放了剩下的代码
  • 所以我在while循环中放了一个if,如果我想让线程停止代码前按钮将是stop==true??
  • catch( InterruptedException e){} ... 叹息 ...

标签: java multithreading wait


【解决方案1】:

其实你有很多解决方案,我会尝试描述其中的一些:

您可以在 main 中创建 2 个静态布尔变量,并在线程中检查它们。

你也可以创建一个静态字符串变量,并在线程中检查它的值。

或者,您可以将 Semaphore 作为静态字段放在主线程中,而在其他线程中您可以访问 tryAcquire() 方法。

在 main 你有这个代码:

static public Semaphore semaphore = new Semaphore(2);

在线程中检查信号量的状态:

while(!semaphore.tryAcquire(2)) {
    Thread.sleep(100);
    if(!semaphore.tryAcquire(1)) {
       //here kill the thread
    }
}

所以在你刚才放的暂停按钮中:

semaphore.acquire(1); 

在停止按钮中:

semaphore.acquire(2);

在开始按钮中:

semaphore.release(2);

【讨论】:

  • 当您说在线程中时,您的意思是在运行方法中?而不是 while(true) 我做检查?
【解决方案2】:

最后我使用了@Roman 的逻辑标志和较早的答案 How to indefinitely pause a thread in Java and later resume it?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2010-12-28
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    相关资源
    最近更新 更多