通过页面jsf中的两个按钮来控制线程的执行,start按钮开启线程,stop按钮停止线程。可是开启线程后,在调用stop按钮停止线程,就是停止不了。
package com.digi.cda.bath.test;public class MyThread extends Thread {

private volatile boolean flag;

public void setFlag(boolean flag) {
this.flag = flag;
} @Override
public void run() {
while(flag) {
System.out.println("doJob");
}
}

public synchronized void stopCurrentThread() {
this.flag = false;
}}希望通过调用stopCurrentThread来停止线程。

解决方案 »

  1.   

    你的start和stop按钮是怎么写的?
      

  2.   

    run里加上一条sleep(0),然后处理InterruptedException。 
    stop或者interrupt后会产生这个异常,你的线程就停下来了。
      

  3.   

    package com.digi.cda.bath.test;public class MyThread extends Thread { private static volatile boolean flag = false;

    @Override
    public synchronized void start() {
    flag = false;
    super.start();
    } @Override
    public void run() {
    while (!flag) {
    System.out.println("doJob");
    }
    } public static  void stopCurrentThread() {
    flag = true;
    }}
    行了,谢谢大家。书还是要多看