我构建了一个应用程序类,它应该可以作为 Thread
运行很高兴听到 Java 开发人员对改进我的编码风格的意见。Main
类(class)。
package com.ozankurt;
public class Main {
public static void main(String[] args) {
Application application = new Application();
application.start();
}
}
应用类:
package com.ozankurt;
import com.ozankurt.utilities.Input;
public class Application implements Runnable {
private CommandHandler commandHandler;
private boolean running;
private volatile Thread thread;
private String threadName = "ApplicationThread";
public Application() {
Handler handler = new Handler(this);
this.commandHandler = new CommandHandler(handler);
this.running = true;
}
public void start() {
if (thread != null) {
System.out.println(threadName + "is already running.");
if (!isRunning())
{
System.out.println("Resuming " + threadName + "...");
setRunning(true);
}
} else {
System.out.println("Starting " + threadName + "...");
thread = new Thread(this, threadName);
thread.start();
System.out.println("Started " + threadName + ".");
}
}
public void stop() {
System.out.println("Halting " + threadName + "...");
setRunning(false);
System.out.println("Halted " + threadName + ".");
}
@Override
public void run() {
while (isRunning()) {
String userInput = Input.readLine();
commandHandler.handle(userInput);
}
}
public boolean isRunning() {
return running;
}
public void setRunning(boolean running) {
this.running = running;
}
}
我读了这个 Java documentation关于如何在不使用 Java 的情况下停止线程
stop
已被弃用的方法,因为它可能会抛出一些异常。据我所知,我们不应该尝试停止线程,而是应该定义一个与线程状态相对应的属性。
就我而言,我定义了一个
boolean running
在我的 Application
类,正如您可以从 run
中的我的代码中读取的那样方法我基本上检查应用程序是否是running
.这意味着我实际上从不停止线程,我只是通过使用 while
来删除它的功能。陈述。这是 Java documentation 中解释的正确方法吗? ?
最佳答案
请不要在 Runnable 上放置启动/停止方法,这只会让读者感到困惑!哈哈!并且不要让这个 runnable 尝试管理它自己的线程,它更令人困惑。
无论如何,第一个问题将是“正在运行” boolean 值上缺少的 volatile 。
第二个问题是 main() 在您启动线程时结束。它确实有效,但这表明您根本不需要任何线程。 main() 线程可以调用一些 Application.loopOnCommands() 或类似的。
第三,stop() 不会中断线程。我假设 readLine() 可以阻塞并且 handle(...) 方法可以很长,因此发出中断信号可以唤醒等待线程。这并不总是会迫使线程退出代码,但如果该代码尊重中断的可能性,它会有所帮助。
关于java - 我的多线程实现好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078437/