我構建的應用程序類,應是可運行的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
方法,已成爲反對,因爲它可能會引發一些例外。
據我瞭解,我們不應該試圖阻止一個線程,而應該定義一個屬性對應於線程的狀態。
在我來說,我在Application
類中定義的boolean running
和你可以從我的代碼在run
方法讀我basicly檢查應用程序是running
。這意味着我實際上從來沒有停止線程,我只能通過使用while
語句來刪除它的功能。這是在Java documentation中解釋的正確方法嗎?
誰需要啓動/停止這個線程?他們爲什麼不能確保他們只啓動其中一個?該應用程序做什麼?多線程部分在哪裏(你可以運行多個部分嗎?如果是這樣,他們如何從輸入中讀取數據)?沒有這一點,目前還不清楚需要做些什麼。 – Thilo
@Thilo我剛剛更新了我的部分代碼,請您再次檢查並查看編輯歷史記錄中的編輯標題。 –
'Application'基本上等待來自命令行的用戶輸入並相應地運行相關的命令。 –