Java/Threads/Thread Status

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

Add a delay

 
 
public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      System.out.println("i = " + i);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {
        ie.printStackTrace();
      }
    }
  }
}





Another way to stop a thread

 
public class AlternateStop extends Object implements Runnable {
  private volatile boolean stopRequested;
  private Thread runThread;
  public void run() {
    runThread = Thread.currentThread();
    stopRequested = false;
    int count = 0;
    while (!stopRequested) {
      System.out.println("Running ... count=" + count);
      count++;
      try {
        Thread.sleep(300);
      } catch (InterruptedException x) {
         // re-assert interrupt
        Thread.currentThread().interrupt();
      }
    }
  }
  public void stopRequest() {
    stopRequested = true;
    if (runThread != null) {
      runThread.interrupt();
    }
  }
  public static void main(String[] args) {
    AlternateStop as = new AlternateStop();
    Thread t = new Thread(as);
    t.start();
    try {
      Thread.sleep(2000);
    } catch (InterruptedException x) {
    }
    as.stopRequest();
  }
}





Another way to suspend and resume

 
public class AlternateSuspendResume extends Object implements Runnable {
  private volatile int firstVal;
  private volatile int secondVal;
  private volatile boolean suspended;
  public boolean areValuesEqual() {
    return (firstVal == secondVal);
  }
  public void run() {
    try {
      suspended = false;
      firstVal = 0;
      secondVal = 0;
      workMethod();
    } catch (InterruptedException x) {
      System.out.println("interrupted in workMethod()");
    }
  }
  private void workMethod() throws InterruptedException {
    int val = 1;
    while (true) {
      // blocks if suspended is true
      waitWhileSuspended();
      stepOne(val);
      stepTwo(val);
      val++;
      // blocks if suspended is true
      waitWhileSuspended();
      Thread.sleep(200); // pause before looping again
    }
  }
  private void stepOne(int newVal) throws InterruptedException {
    firstVal = newVal;
    // simulate some other lengthy process
    Thread.sleep(300);
  }
  private void stepTwo(int newVal) {
    secondVal = newVal;
  }
  public void suspendRequest() {
    suspended = true;
  }
  public void resumeRequest() {
    suspended = false;
  }
  private void waitWhileSuspended() throws InterruptedException {
    while (suspended) {
      Thread.sleep(200);
    }
  }
  public static void main(String[] args) {
    AlternateSuspendResume asr = new AlternateSuspendResume();
    Thread t = new Thread(asr);
    t.start();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException x) {
    }
    for (int i = 0; i < 10; i++) {
      asr.suspendRequest();
      try {
        Thread.sleep(350);
      } catch (InterruptedException x) {
      }
      System.out.println("dsr.areValuesEqual()=" + asr.areValuesEqual());
      asr.resumeRequest();
      try {
        Thread.sleep((long) (Math.random() * 2000.0));
      } catch (InterruptedException x) {
      }
    }
    System.exit(0);
  }
}





Daemon Thread

 
public class DaemonThread implements Runnable {
  public void run() {
    System.out.println("entering run()");
    try {
      System.out.println("in run(): currentThread() is"
          + Thread.currentThread());
      while (true) {
        try {
          Thread.sleep(500);
        } catch (InterruptedException x) {
        }
        System.out.println("in run(): woke up again");
      }
    } finally {
      System.out.println("leaving run()");
    }
  }
  public static void main(String[] args) {
    System.out.println("entering main()");
    Thread t = new Thread(new DaemonThread());
    t.setDaemon(true);
    t.start();
    try {
      Thread.sleep(3000);
    } catch (InterruptedException x) {
    }
    System.out.println("leaving main()");
  }
}





Determining When a Thread Has Finished

 
public class Main {
  public static void main(String[] argv) throws Exception {
    Thread thread = new MyThread();
    thread.start();
    if (thread.isAlive()) {
      System.out.println("Thread has not finished");
    } else {
      System.out.println("Finished");
    }
    long delayMillis = 5000; // 5 seconds
    thread.join(delayMillis);
    if (thread.isAlive()) {
      System.out.println("thread has not finished");
    } else {
      System.out.println("Finished");
    }
    thread.join();
  }
}
class MyThread extends Thread {
  boolean stop = false;
  public void run() {
    while (true) {
      if (stop) {
        return;
      }
    }
  }
}





Interrupt a thread.

 
class MyThread implements Runnable {
  public void run() {
    System.out.println(Thread.currentThread().getName() + " starting.");
    try {
      Thread.sleep(30000);
      for (int i = 1; i < 10; i++) {
        if (Thread.interrupted()) {
          System.out.println("interrupted.");
          break;
        }
        System.out.print(".");
        for (long x = 0; x < 1000; x++)
          System.out.println("/");
      }
    } 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(1000);
    thrd.interrupt();
    thrd2.start();
    Thread.sleep(4000);
    thrd2.interrupt();
  }
}





Is thread alive

 
public class TwoThreadAlive extends Thread {
  public void run() {
    for (int i = 0; i < 10; i++) {
      printMsg();
    }
  }
  public void printMsg() {
    Thread t = Thread.currentThread();
    String name = t.getName();
    System.out.println("name=" + name);
  }
  public static void main(String[] args) {
    TwoThreadAlive tt = new TwoThreadAlive();
    tt.setName("Thread");
    System.out.println("before start(), tt.isAlive()=" + tt.isAlive());
    tt.start();
    System.out.println("just after start(), tt.isAlive()=" + tt.isAlive());
    for (int i = 0; i < 10; i++) {
      tt.printMsg();
    }
    System.out.println("The end of main(), tt.isAlive()=" + tt.isAlive());
  }
}





Monitor a thread"s status.

 
class MyThread extends Thread{
  boolean waiting= true;
  boolean ready= false;
  MyThread() {
  }
  public void run() {
    String thrdName = Thread.currentThread().getName();
    System.out.println(thrdName + " starting.");
    while(waiting) 
      System.out.println("waiting:"+waiting); 
    System.out.println("waiting...");
    startWait(); 
    try {
      Thread.sleep(1000);
    } catch(Exception exc) {
      System.out.println(thrdName + " interrupted.");
    }
    System.out.println(thrdName + " terminating.");
  }
  synchronized void startWait() {
    try {
      while(!ready) wait();
    } catch(InterruptedException exc) {
      System.out.println("wait() interrupted");
    }
  }
  synchronized void notice() {
    ready = true;
    notify();
  }
}
public class Main {
  public static void main(String args[]) throws Exception{
      MyThread thrd = new MyThread();
      thrd.setName("MyThread #1");
      showThreadStatus(thrd);
      thrd.start();
      Thread.sleep(50);
      showThreadStatus(thrd);
      thrd.waiting = false;
      Thread.sleep(50); 
      showThreadStatus(thrd);
      thrd.notice();
      Thread.sleep(50);
      showThreadStatus(thrd);
      while(thrd.isAlive()) 
        System.out.println("alive");
      showThreadStatus(thrd);
  }
  static void showThreadStatus(Thread thrd) {
    System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );
  }
}





Pause the execution

 
class Wait {
  public static void oneSec() {
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  public static void manySec(long s) {
    try {
      Thread.currentThread().sleep(s * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
public class Main{
  public static void main(String args[]) {
    Wait.oneSec();
    Wait.manySec(5);
  }
}





Pause the execution of a thread using sleep()

 
class Wait {
  public static void oneSec() {
    try {
      Thread.currentThread().sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  public static void manySec(long s) {
    try {
      Thread.currentThread().sleep(s * 1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
public class Main {
  public static void main(String args[]) {
    System.out.println("Wait one second");
    Wait.oneSec();
    System.out.println("Done\nWait five seconds");
    Wait.manySec(5);
    System.out.println("Done");
  }
}





Pausing a Thread: set a variable that the thread checks occasionally, call Object.wait()

 
public class Main {
  public static void main(String[] argv) throws Exception {
    MyThread thread = new MyThread();
    thread.start();
    while (true) {
      synchronized (thread) {
        thread.pause = true;
      }
      synchronized (thread) {
        thread.pause = false;
        thread.notify();
      }
    }
  }
}
class MyThread extends Thread {
  boolean pause = false;
  public void run() {
    while (true) {
      synchronized (this) {
        while (pause) {
          try {
            wait();
          } catch (Exception e) {
          }
        }
      }
    }
  }
}





Pausing the Current Thread: a thread can temporarily stop execution.

 
public class Main {
  public static void main(String[] argv) throws Exception {
    long numMillisecondsToSleep = 5000; // 5 seconds
    Thread.sleep(numMillisecondsToSleep);
  }
}





set Uncaught Exception Handler

 
public class Uncaught implements Runnable {
  public static void main(String[] args) {
    Thread thread = new Thread(new Uncaught());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      public void uncaughtException(Thread t, Throwable e) {
        e.printStackTrace();
      }
    });
    thread.start();
  }
  public void run() {
    throw new ArithmeticException();
  }
}





Stopping a Thread: set a variable that the thread checks occasionally

 

public class Main {
  public static void main(String[] argv) throws Exception {
    MyThread thread = new MyThread();
    thread.start();
    thread.stop = true;
  }
}
class MyThread extends Thread {
  boolean stop = false;
  public void run() {
    while (true) {
      if (stop) {
        return;
      }
    }
  }
}





Thread sleep

 
public class TwoThreadSleep extends Thread {
  public void run() {
    Thread t = Thread.currentThread();
    String name = t.getName();
    System.out.println("entered loop() - " + name);
    for (int i = 0; i < 10; i++) {
      try {
        Thread.sleep(200);
      } catch (InterruptedException x) {
        }
      System.out.println("name=" + name);
    }
    System.out.println("leave loop() - " + name);
  }
  public static void main(String[] args) {
    TwoThreadSleep tt = new TwoThreadSleep();
    tt.setName("thread");
    tt.start();
    // pause for a bit
    try {
      Thread.sleep(700);
    } catch (InterruptedException x) {
      // ignore
    }
  }
}





Thread sleep and interrupt

 
public class SleepInterrupt extends Object implements Runnable {
  public void run() {
    try {
      System.out.println("in run() - sleep for 20 seconds");
      Thread.sleep(20000);
      System.out.println("in run() - woke up");
    } catch (InterruptedException x) {
      System.out.println("in run() - interrupted while sleeping");
      return;
    }
    System.out.println("in run() - leaving normally");
  }
  public static void main(String[] args) {
    SleepInterrupt si = new SleepInterrupt();
    Thread t = new Thread(si);
    t.start();
    // Be sure that the new thread gets a chance to
    // run for a while.
    try {
      Thread.sleep(2000);
    } catch (InterruptedException x) {
    }
    System.out.println("in main() - interrupting other thread");
    t.interrupt();
    System.out.println("in main() - leaving");
  }
}





Visual suspend and resume

 
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SwingSuspendResume extends JPanel implements Runnable {
  private static final String[] symbolList = { "|", "/", "-", "\\", "|", "/",
      "-", "\\" };
  private Thread runThread;
  private JTextField symbolTF;
  public SwingSuspendResume() {
    symbolTF = new JTextField();
    symbolTF.setEditable(false);
    symbolTF.setFont(new Font("Monospaced", Font.BOLD, 26));
    symbolTF.setHorizontalAlignment(JTextField.CENTER);
    final JButton suspendB = new JButton("Suspend");
    final JButton resumeB = new JButton("Resume");
    suspendB.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        suspendNow();
      }
    });
    resumeB.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        resumeNow();
      }
    });
    JPanel innerStackP = new JPanel();
    innerStackP.setLayout(new GridLayout(0, 1, 3, 3));
    innerStackP.add(symbolTF);
    innerStackP.add(suspendB);
    innerStackP.add(resumeB);
    this.setLayout(new FlowLayout(FlowLayout.CENTER));
    this.add(innerStackP);
  }
  private void suspendNow() {
    if (runThread != null) { // avoid NullPointerException
      runThread.suspend();
    }
  }
  private void resumeNow() {
    if (runThread != null) { // avoid NullPointerException
      runThread.resume();
    }
  }
  public void run() {
    try {
      // Store this for the suspendNow() and
      // resumeNow() methods to use.
      runThread = Thread.currentThread();
      int count = 0;
      while (true) {
        // each time through, show the next symbol
        symbolTF.setText(symbolList[count % symbolList.length]);
        Thread.sleep(200);
        count++;
      }
    } catch (InterruptedException x) {
      // ignore
    } finally {
      // make sure that the reference to it is also lost.
      runThread = null;
    }
  }
  public static void main(String[] args) {
    SwingSuspendResume vsr = new SwingSuspendResume();
    Thread t = new Thread(vsr);
    t.start();
    JFrame f = new JFrame();
    f.setContentPane(vsr);
    f.setSize(320, 200);
    f.setVisible(true);
    f.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}