gpt4 book ai didi

java - this.start() 不运行威胁在线服务器

转载 作者:行者123 更新时间:2023-11-28 22:25:05 27 4
gpt4 key购买 nike

我有下面的代码。当我在本地服务器(Windows 10 和 Tomcat 8.0.47)上运行它时,它一切正常,在第二台计算机(ubuntu 和 Tomcat 8.5)上也运行正常,一旦我将它部署到外部服务器(数字ocean, Linux 4.4.0-112-generic, Tomcat 8.5.27) 它似乎没有启动威胁。第二次运行启动代码时,它给出了 IllegalThreadStateException。有什么问题可能出在哪里的建议吗?

我的代码:

威胁:

public class Handler extends Thread {

protected DataExchange de;
protected boolean running;

public SearchRequestHandler(DataExchange de) {
this.de = de;
running = false;

}

@Override
public void run() {

while (true) {
synchronized (this) {
running = true;
//do Stuff



try {
running = false;
this.wait();
} catch (InterruptedException e) {
continue;
}
}
}

}

public void startIfNotStarted() {
if (!this.isAlive()) {
this.start();
} else if (!running)
synchronized (this) {
{
this.notify();
}
}
}

}

调用它的类:

public class controller {

private static DataExchange de = new DataExchange();
private static Handler h = new Handler(de);

public static void startThread(Info info) {

de.addInfo(info);

h.startIfNotStarted();

}
}

第二次运行程序时的堆栈跟踪:

java.lang.IllegalThreadStateException java.lang.Thread.start(Thread.java:708) Handler.startIfNotStarted(SearchRequestHandler.java:235) controller.startThreat(Search_controller.java:71) controller.Controller.getMail(Controller.java:30) webServlet.SearchServlet.doPost(SearchServlet.java:110) javax.servlet.http.HttpServlet.service(HttpServlet.java:661) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

最佳答案

/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
if (threadStatus != 0)
throw new IllegalThreadStateException();

在您调用 this.start(); 时,您的线程可能已经死了。请注意,您不能多次启动 Thread 的同一实例。

A thread is alive if it has been started and has not yet died.

此外,无需使用running 字段。你可以通过Thread#getState检查Thread.State:

if (this.getState() == State.NEW) {
this.start();
}

您最好不要在这种情况下调用start。在 Controller 内进行一次正确的调用。 启动一个线程意味着初始化它,而不是恢复它:

class Controller {

private static Handler h = new Handler(de);

static {
h.start(); // it's guaranteed that the statement is called once
}

}

关于java - this.start() 不运行威胁在线服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48926937/

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