Java 我的多线程实现可以吗?

Java 我的多线程实现可以吗?,java,multithreading,Java,Multithreading,我构建了一个应用程序类,它应该可以作为线程运行,如果能听到Java开发人员的意见来改进我的编码风格,那将是一件好事 Mainclass package com.ozankurt; public class Main { public static void main(String[] args) { Application application = new Application(); application.start(); } }

我构建了一个应用程序类,它应该可以作为
线程运行,如果能听到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中停止线程而不使用
stop
方法,该方法已被弃用,因为它可能引发一些异常

据我所知,我们不应该试图停止线程,而是应该定义一个与线程状态相对应的属性


在我的例子中,我在
应用程序
类中定义了一个
布尔运行
,您可以从
运行
方法中读取我的代码,我基本上检查应用程序是否在
运行
。这意味着我实际上从未停止线程,我只使用
while
语句删除它的功能。这是本书中解释的正确方法吗?

请不要在Runnable上设置start/stop方法,它只是在干扰读者!英雄联盟如果没有这个可运行的线程来管理它自己的线程,那就更让人困惑了

无论如何,第一个问题将是“正在运行”布尔值上缺少的volatile

第二个问题是main()在启动线程时结束。当然可以,但这表明你根本不需要任何线程。main()线程可能调用了某个Application.LoopOnCommand()或类似程序


第三,stop()不会中断线程。我假设readLine()可以阻塞,handle(…)方法可以很长,因此发出中断信号可以唤醒等待的线程。这并不总是会迫使线程退出代码,但如果代码允许中断的可能性,这会有所帮助。

谁需要启动/停止此线程?为什么他们不能确保只启动其中一个?这个应用程序做什么?多线程部分在哪里(您可以运行其中的多个吗?如果可以,它们是如何从输入读取的)?没有这些,就不清楚需要做什么。@Thilo我刚刚更新了我代码的那部分,请再次检查并从编辑历史记录中查看我的编辑的
标题
应用程序基本上会等待来自命令行的用户输入并相应地运行相关命令。您可能需要查看codereview.stackexchange.com,由于提高我的编码风格的问题通常都是离题的:)@T3H40谢谢,我会这么做的。:)