Java/Threads/Wait

Материал из Java эксперт
Перейти к: навигация, поиск

A simple demonstration of wait() and notify().

 
class MyResource {
  boolean ready = false;
  synchronized void waitFor() throws Exception {
    System.out.println(Thread.currentThread().getName()+ " is entering waitFor().");
      while (!ready)
        wait();
    System.out.println(Thread.currentThread().getName() + " resuming execution.");
  }
  synchronized void start() {
    ready = true;
    notify();
  }
}
class MyThread implements Runnable {
  MyResource myResource;
  MyThread(String name, MyResource so) {
    myResource = so;
    new Thread(this, name).start();
  }
  public void run() {
   
    try {
      myResource.waitFor();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
public class Main {
  public static void main(String args[]) throws Exception {
    MyResource sObj = new MyResource();
    new MyThread("MyThread", sObj);
    for (int i = 0; i < 10; i++) {
      Thread.sleep(50);
      System.out.print(".");
    }
    sObj.start();
  }
}





Demonstrate join().

 
class MyThread implements Runnable {
  int count;
  MyThread() {
    count = 0;
  }
  public void run() {
    System.out.println("MyThread starting.");
    try {
      do {
        Thread.sleep(500);
        System.out.println("In MyThread, count is " + count);
        count++;
      } while (count < 6);
    } catch (InterruptedException exc) {
      System.out.println("MyThread interrupted.");
    }
    System.out.println("MyThread terminating.");
  }
}
public class Main {
  public static void main(String args[]) {
    System.out.println("Main thread starting.");
    Thread thrd = new Thread(new MyThread());
    thrd.start();
    try {
      thrd.join();
    } catch (InterruptedException exc) {
      System.out.println("Main thread interrupted.");
    }
    System.out.println("Main thread ending.");
  }
}





Launch many programs using Thread and use join() to wait for the completion.

 
class Main2 {
  public static void main(String arg[]) {
    System.out.println("Main2");
  }
}
public class Main {
  public static void main(String arg[]) throws Exception {
    System.out.println("Main");
    Thread t1 = new Thread() {
      public void run() {
        Main2.main(new String[] {});
      }
    };
    t1.start();
    t1.join();
    System.out.println("Main again");
  }
}





Suspend, resume, and stop a thread.

 
class MyThread implements Runnable {
  Thread thrd;
  boolean suspended;
  boolean stopped;
  MyThread(String name) {
    thrd = new Thread(this, name);
    suspended = false;
    stopped = false;
    thrd.start();
  }
  public void run() {
    try {
      for (int i = 1; i < 10; i++) {
        System.out.print(".");
        Thread.sleep(50);
        synchronized (this) {
          while (suspended)
            wait();
          if (stopped)
            break;
        }
      }
    } catch (InterruptedException exc) {
      System.out.println(thrd.getName() + " interrupted.");
    }
    System.out.println("\n" + thrd.getName() + " exiting.");
  }
  synchronized void stop() {
    stopped = true;
    suspended = false;
    notify();
  }
  synchronized void suspend() {
    suspended = true;
  }
  synchronized void resume() {
    suspended = false;
    notify();
  }
}
public class Main {
  public static void main(String args[]) throws Exception {
    MyThread mt = new MyThread("MyThread");
    Thread.sleep(100);
    mt.suspend();
    Thread.sleep(100);
    mt.resume();
    Thread.sleep(100);
    mt.suspend();
    Thread.sleep(100);
    mt.resume();
    Thread.sleep(100);
    mt.stop();
  }
}





Wait for the threads to finish

 

public class Main {
  public static void main(String[] args) throws Exception {
    Thread thread1 = new Thread(new TestThread(1));
    Thread thread2 = new Thread(new TestThread(2));
    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
  }
}
class TestThread implements Runnable {
  int id;
  public TestThread(int id) {
    this.id = id;
  }
  public void run() {
    for (int i = 1; i <= 10; i++) {
      System.out.println("Thread" + id + ": " + i);
    }
  }
}





Waiting on an object

 
public class Main {
  public static void main(String str[]) {
    final Object monitor = new Object();
    new Thread() {
      public void run() {
        try {
          synchronized (monitor) {
            System.out.println("10 seconds ...");
            monitor.wait(10000);
            System.out.println("Wait over");
          }
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    }.start(); 
  }
}





Wait the for the completion of a thread

 
public class Main {
  public static void main(String a[]) throws Exception {
    MyThread tt1 = new MyThread(50);
    MyThread tt2 = new MyThread(75);
    Thread t1 = new Thread(tt1, "Test thread 1");
    Thread t2 = new Thread(tt2, "Test thread 2");
    t1.start();
    t2.start();
    t1.join();
    t2.join();
  }
}
class MyThread implements Runnable {
  int i;
  MyThread(int i) {
    super();
    this.i = i;
  }
  public void run() {
     System.out.println(Thread.currentThread().getName() + " " + i);
  }
}