线程继续,即使它被声明为null JAVA

时间:2015-05-14 01:03:16

标签: java multithreading applet

也许有人可以帮助我 - 在applet中我声明了两个线程的实例,启动了它们,并创建了一个“停止”按钮,声明它们为null。在线程类中,我做了一段时间(这个!= null),按下按钮后线程仍在运行。

这是applet的init方法:

public void init(){
    System.out.println("hi");
    setSize(400,200);                                 // make the applet size big enough for our soup bowl
    s = new Soup();                                   // instantiate the Soup
    p1 = new Producer(this, s);              // declare and instantiate one producer thread - state of NEW
    c1 = new Consumer(this, s);              // declare and instantiate one consumer thread - state of NEW
    p1.start();                                       // start the producer thread
    c1.start();                                       // start the consumer thread

    Button stop = new Button("Stop");
    stop.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            p1 = null;
            c1 = null;
            s.getContents().clear();
        }
    });
    add(stop);
}

以下是线程的运行方法:

public void run() {
    String c;
    try {
        while (this != null) {                           // only put in 10 things so it will stop
            System.out.println("thikns producer != null");
            c = String.valueOf(alphabet.charAt((int)(Math.random() * 26)));   // randomly pick a number to associate with an alphabet letter
            soup.add(c);                                            // add it to the soup
            System.out.println("Added " + c + " to the soup.");     // show what happened in Console
            bowlView.repaint();                                     // show it in the bowl  
            sleep((int)(Math.random() * 2000));  // sleep for a while so it is not too fast to see
        }
    } catch (InterruptedException e) {
        this.interrupt();
    }

}

和此:

  public void run() {
    System.out.println(soup.shouldConsume);
    String c;
    try {
        while(this != null) {              // stop thread when know there are no more coming; here we know there will only be 10
            c = soup.eat();                            // eat it from the soup
            System.out.println("Ate a letter: " + c);  // show what happened in Console
            bowlView.repaint();                        // show it in the bowl  
            sleep((int)(Math.random() * 3000));    // have consumer sleep a little longer or sometimes we never see the alphabets!
        }    
    } catch (InterruptedException e) {
        this.interrupt();
    }

}

为什么这不起作用的任何想法?任何输入都表示赞赏!谢谢大家!

1 个答案:

答案 0 :(得分:1)

while (this != null)永远不会是假的。

将对线程的另一个引用设置为null既不会停止线程也不会导致其this变为空。

您的代码没有意义。

[20世纪90年代末的Java杂志充满了while (Thread.currentThread() == this)次测试。这也没有任何意义。]