java -cp ../../zbnfjax/zbnf.jar org.vishia.zcmd.JZcmd testThread.jz.cmd
pause
exit

==JZcmd==

currdir = scriptdir;

Class Thread = java.lang.Thread; ##used for Thread.sleep(time);



main(){

  call testThreadOutputSynchronized();
  call testJoin();
}



sub testThreadOutputSynchronized(){
  java org.vishia.util.DataAccess.debugIdent("Thread");

  Thread myThread = {
    <+ >The thread starts an output line, it needs time (sleeps here) <&Thread.sleep(100):""> but is not disturbed<.n+>
  }
  <+>The main thread starts an output simultaneously, sleeps <&Thread.sleep(100):""> but the output is not disturbed because it is synchronized.<.n+>
  Thread.sleep(100); ##switch to the second thread now.
  ##alternatively:
  myThread.join(0);
  <+>Second thread is finished. testThreadOutputSynchronized now finished. <.n+>
}



sub testJoin(){
  Filepath parseInput = "../../examples_ZBNF_core/BillOfMaterial/billOfMaterial.txt";
  Filepath syntax = "../../examples_ZBNF_core/BillOfMaterial/billOfMaterial.zbnf";
  
  Obj data;   //for parse result
  
  ##The parsing should be done in an extra thread, executing parallel on a mulitcore CPU
  Thread myThread = 
  {  
    Obj zbnfParser = java new org.vishia.zbnf.ZbnfParser(jzcmd.log);  ##create the parser instance
    zbnfParser.setSyntaxFile(File:<:><&syntax.absfile()><.>);                       ##set the syntax
    Bool cont = 1;
    Obj cmd1;
    while(cont){
      cmd1 = myThread.awaitcmd(100000);        ##waits for a command given with sendcmd() from another thread. NOTE: cmd is a keyword, use cmd1 as variable name.
      if(cmd1.cmd == "parse") {
        String inputfile = cmd1.data;          ##filename given as data of the command.
        <+out>parse: <&inputfile><.n+>
        Bool ok = zbnfParser.parseFile(File:&inputfile);             ##parse
        if(not ok){
          <+out><&zbnfParser.getSyntaxErrorReport()><.+>
          myThread.sendmsg("nok", null);      
        } else {
          data = zbnfParser.getResultTree();
          myThread.sendmsg("ok", null);      
        }
      } elsif(cmd1.cmd == "finish"){
        cont = 0;  
      } 
      else { <+out>testJoin.Thread - unexpected command; <&cmd1><.n+> }
    }
    onerror{ <+out><&error><.n+> myThread.sendmsg(<:>error<&error><.>); }
  }
  
  ##continue in the main thread:
  //
  ##start activity in the thread via a command:
  myThread.sendcmd("parse", parseInput.absfile());
  //
  ##...the main thread can do any other action simultaneously
  Obj result = myThread.awaitmsg(60000);
  if(result.cmd == "ok"){
    <+out>...has parsed, data ready to process<.n+>
  } else {
    <+out>...parsing error: <&result.cmd><.n+>
  }  
  myThread.sendcmd("finish", null);
  myThread.join(10000);  //after 1 minute it should be ready    ##wait for the thread, with long timeout, it should be worked.
  if(data){
    <+out>...has finished, data ready to process<.n+>
  }
}
