1010import java .util .ArrayList ;
1111import java .util .List ;
1212
13- public class Batchprocessor extends Thread {
13+ public class Batchprocessor implements Runnable {
1414 List <String > cmdList = new ArrayList <>();
1515 private CmdLineUI cmdLineUI ;
1616 private PrintStream printStream ;
1717 private ByteArrayInputStream inputStream ;
18+ private Thread runningThread ;
1819
1920 public Batchprocessor () {
2021 this (true );
@@ -31,8 +32,24 @@ public void addCommand(String cmd) {
3132 this .cmdList .add (cmd );
3233 }
3334
34- @ Override
35- public void run () {
35+ public void execute () {
36+ this .prepareExecution ();
37+ this .doExecution ();
38+ }
39+
40+ public void executeAsThread () {
41+ this .prepareExecution ();
42+ this .runningThread = new Thread (this );
43+ this .runningThread .start ();
44+ }
45+
46+ public void join () throws InterruptedException {
47+ if (this .runningThread != null && this .runningThread .isAlive ()) {
48+ this .runningThread .join ();
49+ }
50+ }
51+
52+ private void prepareExecution () {
3653 // prepare output
3754 ByteArrayOutputStream baos = new ByteArrayOutputStream ();
3855 PrintStream ps = new PrintStream (baos );
@@ -41,11 +58,16 @@ public void run() {
4158 ps .println (cmd );
4259 }
4360
61+ // clean cmd list
62+ this .cmdList = new ArrayList <>();
63+
4464 ByteArrayInputStream bais = new ByteArrayInputStream (baos .toByteArray ());
4565
4666 this .printStream = System .out ;
4767 this .inputStream = bais ;
68+ }
4869
70+ private void doExecution () {
4971 this .cmdLineUI .runCommandLoop (this .printStream , this .inputStream );
5072
5173 // in any case - give it some time to tidy up
@@ -54,5 +76,12 @@ public void run() {
5476 } catch (InterruptedException e ) {
5577 // ignore
5678 }
79+
80+ this .runningThread = null ;
81+ }
82+
83+ @ Override
84+ public void run () {
85+ this .doExecution ();
5786 }
5887}
0 commit comments