JFRAME的小窗口程序,里面有一个循环函数find(),因为其运行缓慢,所以有时要直接退出窗口,但此时按窗口的关闭却无法响应,必须等到find()执行完毕,加上windowsclosing函数和system.exit(0)也无效,请问有什么好的办法可以直接点击关闭键时就退出循环将窗口关闭?是多线程思路吗?怎么去实现?

解决方案 »

  1.   

    单独启用一个线程去执行find()函数...
      

  2.   


    class ThreadTest implements Runnable{
    static boolean flag=true;
    public void run(){
    while(flag){
    try {
    Thread.sleep(500);
    System.out.println("haha");
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }}
    class Main {
    public static void main(String[] args) throws Exception{
    Thread a=new Thread(new ThreadTest());
    a.start();
    for(int i=0;i<3;i++){
    Thread.sleep(1000);
    System.out.println("for ");
    }
    if(a.isAlive()){
    ThreadTest.flag=false;
    System.out.println("destroyed");
    }
    else{
    System.out.println("still alive");
    }
    }
    }