我现在写了个子线程,里面有个死循环,不停地从数据库读出需要的数据进行处理,界面上有个关闭按钮,请问该怎么编写,使这个按钮点击之后可以关闭这个子线程。主要就是怎么关闭子线程。

解决方案 »

  1.   

    在线程里设置一个标志,然后判断就行了,比如boolean stop = false;
    。while(!stop){
      // 你的一直处理的代码。
    }你要做的就是在其它地方将这个 stop 设置为true 就可以了。
    如果这个线程只有一个,你可以用
    static boolean stop = false;这样访问起来就更简单了!
      

  2.   

    我这样子设置的,但是这个线程停止不了啊!
    class Mythread extends Thread{
    private volatile boolean stop=false;  public void threadStop(){
     stop=true;
     }
    public void run(){
    try{
    //init();
    synchronized(this){
    while(stop){
    getdate();
    }
    }
    }catch(Exception e){}
    }我在主线程中调用Mythread.threadStop()中止不了
      

  3.   

    那要看你的 Mythread 是不是阻塞在 getdate() 里面了。
      

  4.   

    java 5.0 的新特性里面有了新的线程包。 可以让线程抛异常、返回值、和停止。我给你断代码。import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;public class TestNewThread {



    public static void main(String[] args)
    throws Exception{
    ExecutorService es = Executors.newCachedThreadPool(); //获得一个线程池。
        Future f = es.submit( new Callable(){ //这是一个接口call就是线程执行时调用的方法(相当于runnable).
    @Override
    public Object call() throws Exception {


    for(int i=0;i<10;i++){
    System.out.println( Thread.currentThread().getId() );
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return "5.0新线程";
    }
    }  
    );

      // f.cancel( true ); //停止
       String str = (String)f.get();//获得线程返回值
       System.out.println(str);
    }
    }es.submit( callable  ) 就是启动一个线程。可以启动多个线程(调多次submit)
      

  5.   


    把这个指示变量设置成volatile类型,这样使线程每次访问该变量时强近它从共享内存中重读变量的值,而不是读它的副本
      

  6.   

    你的程序判断变量写错了,给你改了下,代码如下:
    class Mythread extends Thread{
    private volatile boolean stop=true;public void threadStop(){
    stop=false;
    }
    public void run(){
    try{
    //init();
    synchronized(this){
    while(stop){
    getdate();
    }
    }
    }catch(Exception e){}

    如果这样都还不行,还有一个比较贱的办法,但是会影响你的程序效率,代码如下:
    class Mythread extends Thread{
    private volatile boolean stop=true;public void threadStop(){
    stop=false;
    }
    public void run(){
    try{
    //init();
    synchronized(this){
    while(stop){
    if(stop==false){
    break;
    }else{
    getdate();
    }
    }
    }
    }catch(Exception e){}
      

  7.   

    这个线程中止问题确实必须使用volatile,起码我在《Thinking in java》里面看到是这么说的