java - How to tell main thread that part of thread job is done -


is true notify works after thread finished? in code below can't notification until comment while (true). how tell main thread part of thread job done?

public class threadmain {     public thread reader;     private class serialreader implements runnable {         public void run() {             while (true) {                 try {                     thread.sleep(3000);                                     synchronized(this) {                         system.out.println("notifying");                         notify();                         system.out.println("notifying done");                     }                                 } catch (exception e) {                     system.out.println(e);                 }                             }         }     }      threadmain() {         reader = new thread(new serialreader());     }      public static void main(string [] args) {         threadmain d= new threadmain();             d.reader.start();         synchronized(d.reader) {             try {                     d.reader.wait();                 system.out.println("got notify");             } catch (exception e) {                  system.out.println(e);             }             }             } } 

you should try avoid using wait , notify newer versions of java, they're difficult right. try using blockingqueue instead

public class threadmain {     public final blockingqueue<boolean> queue = new linkedblockingqueue<>();     private class serialreader implements runnable {         public void run() {             while (true) {                 try {                     thread.sleep(3000);                                     system.out.println("notifying");                     queue.offer(boolean.true);                     system.out.println("notifying done");                             } catch (exception e) {                     system.out.println(e);                 }                             }         }     }      threadmain() {         reader = new thread(new serialreader());     }      public static void main(string [] args) {         threadmain d= new threadmain();             d.reader.start();         try {                 d.queue.take(); // block until put in queue             system.out.println("got notify");         } catch (exception e) {              system.out.println(e);         }               } } 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

php - joomla get content in onBeforeCompileHead function -