gpt4 book ai didi

java - 即使线程被声明为 null JAVA,线程仍继续运行

转载 作者:行者123 更新时间:2023-12-01 11:33:35 26 4
gpt4 key购买 nike

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

这是小程序的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();
}

}

有什么想法为什么这不起作用吗?任何意见表示赞赏!谢谢大家!

最佳答案

while (this != null) 永远不能为 false。

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

你的代码没有意义。

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

关于java - 即使线程被声明为 null JAVA,线程仍继续运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227638/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com