Java - general

thread, wait() and notify()

The example shows a MasterThread which starts a ChildThread and then „gets some sleep“. Afterwards, it is waked up by its own ChildThread after its completion:

package com.sowas.javawiki.waitnotify;
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class MasterThread extends Thread {
   private static ExecutorService service = Executors.newCachedThreadPool();
 
   @Override
   public void run() {
      System.out.println("MasterThread starts");
      synchronized(this) {
         service.execute(new ChildThread(this));
         try {
            wait();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
      System.out.println("MasterThread ends");
   }
 
   public static void main(String[] args) {
      service.execute(new MasterThread());
   }
}
public class ChildThread implements Runnable {
   private MasterThread masterThread;
 
   ChildThread(MasterThread masterThread) {
      this.masterThread = masterThread;
   }
 
   @Override
   public void run() {
      try {
         System.out.println("ChildThread starts");
         // the ChildThread is running here...
         System.out.println("ChildThread ends");
      } finally {
         // inform Masterthread that ChildThread is ready:
         synchronized (masterThread) {
            masterThread.notify();
         }
      }
   }
}

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007