Java by API/java.lang/Thread

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

new Thread(Runnable target, String name)

  
/*
 * Output:
 * 
 * Got: 0
 * Got: 0
 * Got: 0
 * ...
 */
class Queue {
  int n;
  synchronized int get() {
  System.out.println("Got: " + n);
  return n;
  }
  synchronized void put(int n) {
  this.n = n;
  System.out.println("Put: " + n);
  }
}
class Consumer implements Runnable {
  Queue q;
  Consumer(Queue q) {
  this.q = q;
  new Thread(this, "Consumer").start();
  }
  public void run() {
  while(true) {
      q.get();
  }
  }
}
public class MainClass {
  public static void main(String args[]) {
  Queue q = new Queue();
  new Consumer(q);
  }
}





Thread.activeCount()

  
/*
 * Output:
 * 
current thread: Thread[My Thread,1,main]
currently active threads: 1
0: Thread[My Thread,1,main]
java.lang.Exception: Stack trace
  at java.lang.Thread.dumpStack(Thread.java:1158)
  at MainClass.main(MainClass.java:23)
 * 
 
 *  
 */
public class MainClass {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    t.setName("My Thread");
    t.setPriority(1);
    System.out.println("current thread: " + t);
    int active = Thread.activeCount();
    System.out.println("currently active threads: " + active);
    Thread all[] = new Thread[active];
    Thread.enumerate(all);
    for (int i = 0; i < active; i++) {
      System.out.println(i + ": " + all[i]);
    }
    Thread.dumpStack();
  }
}





Thread.currentThread()

  
/*
 * Output: 
currentThread: Thread[main,5,main]
Thread created: Thread[Demo Thread,5,main]
5
4
3
2
1
exiting child thread

 */
public class MainClass implements Runnable {
  MainClass() {
    Thread ct = Thread.currentThread();
    Thread t = new Thread(this, "Demo Thread");
    System.out.println("currentThread: " + ct);
    System.out.println("Thread created: " + t);
    t.start();
  }
  public void run() {
    for (int i = 5; i > 0; i--) {
      System.out.println("" + i);
    }
    System.out.println("exiting child thread");
  }
  public static void main(String args[]) {
    new MainClass();
  }
}





Thread.dumpStack()

  
/*
 * Output:
 * 
current thread: Thread[My Thread,1,main]
currently active threads: 1
0: Thread[My Thread,1,main]
java.lang.Exception: Stack trace
  at java.lang.Thread.dumpStack(Thread.java:1158)
  at MainClass.main(MainClass.java:23)
 * 
 
 *  
 */
public class MainClass {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    t.setName("My Thread");
    t.setPriority(1);
    System.out.println("current thread: " + t);
    int active = Thread.activeCount();
    System.out.println("currently active threads: " + active);
    Thread all[] = new Thread[active];
    Thread.enumerate(all);
    for (int i = 0; i < active; i++) {
      System.out.println(i + ": " + all[i]);
    }
    Thread.dumpStack();
  }
}





Thread.enumerate(Thread[] tarray)

  
/*
 * Output:
 * 
current thread: Thread[My Thread,1,main]
currently active threads: 1
0: Thread[My Thread,1,main]
java.lang.Exception: Stack trace
  at java.lang.Thread.dumpStack(Thread.java:1158)
  at MainClass.main(MainClass.java:23)
 * 
 
 *  
 */
public class MainClass {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    t.setName("My Thread");
    t.setPriority(1);
    System.out.println("current thread: " + t);
    int active = Thread.activeCount();
    System.out.println("currently active threads: " + active);
    Thread all[] = new Thread[active];
    Thread.enumerate(all);
    for (int i = 0; i < active; i++) {
      System.out.println(i + ": " + all[i]);
    }
    Thread.dumpStack();
  }
}





Thread: getStackTrace()

 
public class Main {
 public static void main(String args[]) {
   anotherLayout();
 }
 public static void anotherLayout(){
   new Main().doit();
 }
 public void doit() {
    System.out.println(
       Thread.currentThread().getStackTrace()[3].getMethodName());
 }
}





Thread: getThreadGroup()

  
class Main {
  public static void main(String[] args) throws Exception {
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    MyThread mt1 = new MyThread(tg, "first");
    MyThread mt2 = new MyThread(tg, "second");
    mt1.start();
    mt2.start();
    ThreadGroup parent = tg.getParent();
    Thread[] list = new Thread[parent.activeCount()];
    int count = parent.enumerate(list, true);
    String[] thdinfo = new String[count];
    for (int i = 0; i < count; i++)
      thdinfo[i] = list[i].toString();
    mt1.join();
    mt2.join();
    for (int i = 0; i < count; i++)
      System.out.println(thdinfo[i]);
  }
}
class MyThread extends Thread {
  MyThread(ThreadGroup tg, String name) {
    super(tg, name);
  }
  public void run() {
    for (char c = "A"; c <= "Z"; c++)
      System.out.println(c);
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
    }
  }
}





Thread: getUncaughtExceptionHandler()

  
import java.util.ArrayList;
public class Main implements Runnable {
  static class OverrideExceptionHandler implements Thread.UncaughtExceptionHandler {
    public void uncaughtException(Thread t, Throwable e) {
      alertAdministrator(e);
    }
  }
  public static void alertAdministrator(Throwable e) {
    // Use Java Mail to send the administrator"s pager an email
    System.out.println("Adminstrator alert!");
    e.printStackTrace();
  }
  public static void main(String[] args) {
    Thread t = new Thread(new Main());
    t.setUncaughtExceptionHandler(new OverrideExceptionHandler());
    System.out.println(t.getUncaughtExceptionHandler());
    t.start();
  }
  public void run() {
    ArrayList al = new ArrayList();
    while (true) {
      al.add(new byte[1024]);
    }
  }
}





Thread: interrupt()

  
class TryThread extends Thread {
  public TryThread(String firstName, String secondName, long delay) {
    this.firstName = firstName;
    this.secondName = secondName;
    aWhile = delay;
  }
  public void run() {
    try {
      while (true) {
        System.out.print(firstName);
        sleep(aWhile);
        System.out.print(secondName + "\n");
      }
    } catch (InterruptedException e) {
      System.out.println(firstName + secondName + e);
    }
  }
  private String firstName;
  private String secondName;
  private long aWhile;
}
public class Main {
  public static void main(String[] args) {
    Thread first = new TryThread("A ", "a ", 200L);
    Thread second = new TryThread("B ", "b ", 300L);
    Thread third = new TryThread("C ", "c ", 500L);
    first.start();
    second.start();
    third.start();
    try {
      Thread.sleep(3000);
      first.interrupt();
      second.interrupt();
      third.interrupt();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}





Thread: isAlive()

  
class NewThread implements Runnable {
  String name; // name of thread
  Thread t;
  NewThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start(); // Start the thread
  }
  public void run() {
    try {
      for (int i = 5; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }
}
class DemoJoin {
  public static void main(String args[]) {
    NewThread ob1 = new NewThread("One");
    System.out.println("Thread One is alive: " + ob1.t.isAlive());
  }
}





Thread: isDaemon()

  
class MyThread extends Thread {
  MyThread() {
    setDaemon(true);
  }
  public void run() {
    boolean isDaemon = isDaemon();
    System.out.println("isDaemon:" + isDaemon);
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Thread thread = new MyThread();
    thread.setDaemon(true);
    thread.start();
  }
}





Thread: join() (Using join() to wait for threads to finish)

  
/*
 * Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Two: 5
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Three: 5
Two: 4
Three: 4
One: 4
One: 3
Three: 3
Two: 3
One: 2
...
...  
 */
class MyThread implements Runnable {
  String name; // name of thread
  Thread t;
  MyThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start();
  }
  public void run() {
    try {
      for (int i = 5; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }
}
public class MainClass {
  public static void main(String args[]) {
    MyThread ob1 = new MyThread("One");
    MyThread ob2 = new MyThread("Two");
    MyThread ob3 = new MyThread("Three");
    System.out.println("Thread One is alive: " + ob1.t.isAlive());
    System.out.println("Thread Two is alive: " + ob2.t.isAlive());
    System.out.println("Thread Three is alive: " + ob3.t.isAlive());
    try {
      System.out.println("Waiting for threads to finish.");
      ob1.t.join();
      ob2.t.join();
      ob3.t.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }
    System.out.println("Thread One is alive: " + ob1.t.isAlive());
    System.out.println("Thread Two is alive: " + ob2.t.isAlive());
    System.out.println("Thread Three is alive: " + ob3.t.isAlive());
    System.out.println("Main thread exiting.");
  }
}





Thread.MAX_PRIORITY

  
/*
 * Output:
 * 
    29465957 vs. -1589812543
 *   
 * 
 *  
 */
class MyThread implements Runnable {
  public int click = 0;
  private Thread t;
  private boolean running = true;
  public MyThread(int p) {
    t = new Thread(this);
    t.setPriority(p);
  }
  public void run() {
    while (running) {
      click++;
    }
  }
  public void stop() {
    running = false;
  }
  public void start() {
    t.start();
  }
}
public class MainClass {
  public static void main(String args[]) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    MyThread hi = new MyThread(Thread.NORM_PRIORITY + 2);
    MyThread lo = new MyThread(Thread.NORM_PRIORITY - 2);
    lo.start();
    hi.start();
    try {
      Thread.sleep(10000);
    } catch (Exception e) {
    }
    lo.stop();
    hi.stop();
    System.out.println(lo.click + " vs. " + hi.click);
  }
}





Thread.NORM_PRIORITY

  
/*
 * Output:
 * 
    29465957 vs. -1589812543
 *   
 * 
 *  
 */
class MyThread implements Runnable {
  public int click = 0;
  private Thread t;
  private boolean running = true;
  public MyThread(int p) {
    t = new Thread(this);
    t.setPriority(p);
  }
  public void run() {
    while (running) {
      click++;
    }
  }
  public void stop() {
    running = false;
  }
  public void start() {
    t.start();
  }
}
public class MainClass {
  public static void main(String args[]) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    MyThread hi = new MyThread(Thread.NORM_PRIORITY + 2);
    MyThread lo = new MyThread(Thread.NORM_PRIORITY - 2);
    lo.start();
    hi.start();
    try {
      Thread.sleep(10000);
    } catch (Exception e) {
    }
    lo.stop();
    hi.stop();
    System.out.println(lo.click + " vs. " + hi.click);
  }
}





Thread: run()

  
/*
 * Output:
Hello
Hello
Hello
 */
class ThreadX extends Thread {
  
  public void run() {
    try {
      while(true) {
        Thread.sleep(2000);
        System.out.println("Hello");
      }
    }
    catch(InterruptedException ex) {
      ex.printStackTrace();
    }
  }
}
public class MainClass {
  public static void main(String args[]) {
    
    ThreadX tx = new ThreadX();
    tx.start();
  }
}





Thread: setDaemon(boolean b)

  
import static java.util.concurrent.TimeUnit.SECONDS;
public class MainClass extends Thread {
  // This field is volatile because two different threads may access it
  volatile boolean keepRunning = true;
  public MainClass() {
    setDaemon(true);
  }
  public void run() {
    while (keepRunning) {
      long now = System.currentTimeMillis();
      System.out.printf("%tr%n", now);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        return;
      }
    }
  }
  public void pleaseStop() {
    keepRunning = false;
  }
  public static void main(String[] args) {
    MainClass thread = new MainClass();
    thread.start();
    try {
      SECONDS.sleep(10);
    } catch (InterruptedException ignore) {
    }
    thread.pleaseStop();
  }
}





Thread: setDaemon(boolean on)

  
class MyThread extends Thread {
  MyThread() {
    setDaemon(true);
  }
  public void run() {
    boolean isDaemon = isDaemon();
    System.out.println("isDaemon:" + isDaemon);
  }
}
public class Main {
  public static void main(String[] argv) throws Exception {
    Thread thread = new MyThread();
    thread.setDaemon(true);
    thread.start();
  }
}





Thread: setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh)

  
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainClass extends JFrame {
  public static void main(String[] args) {
    new MainClass().setVisible(true);
  }
  public MainClass() {
    Container cp = getContentPane();
    JButton crasher = new JButton("Crash");
    cp.add(crasher);
    crasher.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        throw new RuntimeException("You asked for it");
      }
    });
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      public void uncaughtException(Thread t, Throwable ex) {
        System.out.println("You crashed thread " + t.getName());
        System.out.println("Exception was: " + ex.toString());
      }
    });
    pack();
  }
}





Thread: setName(String name)

  
/*
 * Output:
 * 
current thread: Thread[My Thread,1,main]
currently active threads: 1
0: Thread[My Thread,1,main]
java.lang.Exception: Stack trace
  at java.lang.Thread.dumpStack(Thread.java:1158)
  at MainClass.main(MainClass.java:23)
 * 
 
 *  
 */
public class MainClass {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    t.setName("My Thread");
    t.setPriority(1);
    System.out.println("current thread: " + t);
    int active = Thread.activeCount();
    System.out.println("currently active threads: " + active);
    Thread all[] = new Thread[active];
    Thread.enumerate(all);
    for (int i = 0; i < active; i++) {
      System.out.println(i + ": " + all[i]);
    }
    Thread.dumpStack();
  }
}





Thread: setPriority(int newPriority)

  
/*
 * Output:
 * 
current thread: Thread[My Thread,1,main]
currently active threads: 1
0: Thread[My Thread,1,main]
java.lang.Exception: Stack trace
  at java.lang.Thread.dumpStack(Thread.java:1158)
  at MainClass.main(MainClass.java:23)
 * 
 
 *  
 */
public class MainClass {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    t.setName("My Thread");
    t.setPriority(1);
    System.out.println("current thread: " + t);
    int active = Thread.activeCount();
    System.out.println("currently active threads: " + active);
    Thread all[] = new Thread[active];
    Thread.enumerate(all);
    for (int i = 0; i < active; i++) {
      System.out.println(i + ": " + all[i]);
    }
    Thread.dumpStack();
  }
}





Thread: setUncaughtExceptionHandler(UncaughtExceptionHandler eh)

  
public class MainClass {
  public static void main(String[] args) {
    Thread thread = new Thread(new MyThread());
    thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
      public void uncaughtException(Thread t, Throwable e) {
        System.out.println(t + " threw exception: " + e);
      }
    });
    thread.start();
  }
}
class MyThread implements Runnable {
  public void run() {
    throw new ArithmeticException();
  }
}





Thread: start

  
/*
 * Output:
 *  run
 */
class caller implements Runnable {
  String msg;

  public caller(String s) {
    msg = s;
    new Thread(this).start();
  }
  public void run() {
    System.out.println("run");
  }
}
public class MainClass {
  public static void main(String args[]) {
    new caller("Hello");
  }
}





Thread: stop

  
/*
 * Output:
 * 
    29465957 vs. -1589812543
 *   
 * 
 *  
 */
class MyThread implements Runnable {
  public int click = 0;
  private Thread t;
  private boolean running = true;
  public MyThread(int p) {
    t = new Thread(this);
    t.setPriority(p);
  }
  public void run() {
    while (running) {
      click++;
    }
  }
  public void stop() {
    running = false;
  }
  public void start() {
    t.start();
  }
}
public class MainClass {
  public static void main(String args[]) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    MyThread hi = new MyThread(Thread.NORM_PRIORITY + 2);
    MyThread lo = new MyThread(Thread.NORM_PRIORITY - 2);
    lo.start();
    hi.start();
    try {
      Thread.sleep(10000);
    } catch (Exception e) {
    }
    lo.stop();
    hi.stop();
    System.out.println(lo.click + " vs. " + hi.click);
  }
}





Threah.sleep(long millis)

  
/*
 * Output:
 * 
   ]
 */
public class MainClass {
  public static void main(String args[]) {
    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }
    System.out.println("]");
  }
}