java - Is my implementation of multi-threading okay? -


i built application class should runnable thread , nice hear opinions of java developers improve coding style.

main class.

package com.ozankurt;  public class main {      public static void main(string[] args) {          application application = new application();          application.start();      } } 

application class:

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 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;     } } 

i read java documentation how stop threads in java without using stop method has become deprecated because might throw exceptions.

as far understand shouldn't try stop thread , instead should define property corresponding state of thread.

in case defined boolean running in application class , can read code in run method basicly check if application running. mean never stop thread, remove functionality using while statement. correct approach explained in java documentation?

please don't put start/stop method on runnable, it's messing reader! lol! , don't have runnable try manage it's own thread, it's more confusing.

anyhow, 1st issue missing volatile on 'running' boolean.

2nd issue main() ends while started thread. works, sure, shows didn't need thread @ all. main() thread have called application.looponcommands() or similar.

3rd, stop() doesn't interrupt thread. i'm assuming readline() can block , handle(...) method can long, signaling interrupt can wake waiting threads. not going force thread out of code, can if code honoring possibility interruptions.


Comments