在页面卸载时终止java applet线程

时间:2010-01-25 17:07:40

标签: java multithreading applet

我在终止线程方面遇到了问题。问题是我使用applet线程来访问JS DOM并操纵span的innerHTML以将Thread Name作为innerHTML。它工作正常,直到我不断刷新页面,但如果我不给它200ms的睡眠并转到另一个没有任何applet的页面,它将在firebug控制台中给我一个错误:

document.getElementById("userName") is null

我怀疑的是,虽然我在停止时发送了一个中断,并且我也通过在run while循环中设置一个运行的标志变量来尝试相同的操作,但是线程的执行速度比JVM卸载它的时间要快得多在浏览器中更改我的页面,但applet仍在尝试查找具有id userName的元素。

这是真的吗? 它有什么工作吗? 有没有办法知道目前有多少线程在运行? 是否有任何kill all命令发送到destroy()?

我搜索了很多,看过java线程和applet的所有API,无法让它工作。

以下是代码:

import java.applet.Applet;
import netscape.javascript.*;

//No need to extend JApplet, since we don't add any components;
//we just paint.
public class firstApplet extends Applet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    firstThread first;
    boolean running = false;

    public class firstThread extends Thread{
        JSObject win;
        JSObject doc;
        firstThread second;

        public firstThread(JSObject window){
            this.win = window;
        }
        public void run() {
            try{
                System.out.println("running... ");

                while (!isInterrupted()){

                    doc = (JSObject) win.getMember("document"); 
                    String userName = Thread.currentThread().getName();
                    //String userName = "John Doe";
                    String S = "document.getElementById(\"userName\").innerHTML = \""+userName+"\";";
                    doc.eval(S);
                    Thread.sleep(5);
                }
            }catch(Exception e){
                System.out.println("exception in first thread... ");
                e.printStackTrace();
            }
        }
    }

    public void init() {
        System.out.println("initializing... ");
    }

    public void start() {
        System.out.println("starting... ");
        JSObject window = JSObject.getWindow(this);

        first = new firstThread(window);
        first.start();
        running = true;
    }

    public void stop() {
        first.interrupt();
        first = null;
        System.out.println("stopping... ");
    }

    public void destroy() {
        if(first != null){
            first = null;
        }
        System.out.println("preparing for unloading...");
    }
}

由于

2 个答案:

答案 0 :(得分:0)

你不能只检查document.getElementById(“userName”)是否为空,只有在它不是时才尝试设置它??

答案 1 :(得分:0)

相关问题