Java Tutorial/Thread/Suspend resume

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

Interrupt a thread.

class MyThread implements Runnable {
  public void run() {
    try {
      Thread.sleep(30000);
      for (int i = 1; i < 10; i++) {
        if (Thread.interrupted()) {
          System.out.println("interrupted.");
          break;
        }
      }
    } catch (Exception exc) {
      System.out.println(Thread.currentThread().getName() + " interrupted.");
    }
    System.out.println(Thread.currentThread().getName() + " exiting.");
  }
}
public class Main {
  public static void main(String args[]) throws Exception {
    Thread thrd = new Thread(new MyThread(), "MyThread #1");
    Thread thrd2 = new Thread(new MyThread(), "MyThread #2");
    thrd.start();
    Thread.sleep(100);
    thrd.interrupt();
    thrd2.start();
    Thread.sleep(400);
    thrd2.interrupt();
  }
}





Suspending and resuming a thread the modern way.

class NewThread implements Runnable {
  String name;
  Thread t;
  boolean suspendFlag;
  NewThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    suspendFlag = false;
    t.start();
  }
  public void run() {
    try {
      for (int i = 15; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(200);
        synchronized (this) {
          while (suspendFlag) {
            wait();
          }
        }
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }
  void mysuspend() {
    suspendFlag = true;
  }
  synchronized void myresume() {
    suspendFlag = false;
    notify();
  }
}
class SuspendResume {
  public static void main(String args[]) {
    NewThread ob1 = new NewThread("One");
    NewThread ob2 = new NewThread("Two");
    try {
      Thread.sleep(1000);
      ob1.mysuspend();
      System.out.println("Suspending thread One");
      Thread.sleep(1000);
      ob1.myresume();
      System.out.println("Resuming thread One");
      ob2.mysuspend();
      System.out.println("Suspending thread Two");
      Thread.sleep(1000);
      ob2.myresume();
      System.out.println("Resuming thread Two");
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }
    try {
      System.out.println("Waiting for threads to finish.");
      ob1.t.join();
      ob2.t.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }
    System.out.println("Main thread exiting.");
  }
}