2016-01-29 37 views
2

我構建的應用程序類,應是可運行的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中解釋的正確方法嗎?

+0

誰需要啓動/停止這個線程?他們爲什麼不能確保他們只啓動其中一個?該應用程序做什麼?多線程部分在哪裏(你可以運行多個部分嗎?如果是這樣,他們如何從輸入中讀取數據)?沒有這一點,目前還不清楚需要做些什麼。 – Thilo

+0

@Thilo我剛剛更新了我的部分代碼,請您再次檢查並查看編輯歷史記錄中的編輯標題。 –

+0

'Application'基本上等待來自命令行的用戶輸入並相應地運行相關的命令。 –

回答

0

請不要在Runnable上放置啓動/停止方法,它只是搞亂讀者!大聲笑!並沒有這個可運行的嘗試來管理它自己的線程,它更令人困惑。

無論如何,第一個問題將是「運行」布爾值上丟失的易失性。

第二個問題是您的main()在您啓動線程時結束。它確實有效,但是這表明你根本不需要任何線程。 main()線程可能調用了一些Application.loopOnCommands()或類似的東西。

3,停止()不會中斷線程。我假設readLine()可以阻塞,並且handle(...)方法可以很長,因此發信號通知中斷可以喚醒等待的線程。這並不總是會強制代碼中的一個線程,但如果代碼承認中斷的可能性,它可以提供幫助。