Java Tutorial/Thread/Thread Properties

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

Controlling the main Thread.

class CurrentThreadDemo {
  public static void main(String args[]) {
    Thread t = Thread.currentThread();
    System.out.println("Current thread: " + t);
    t.setName("My Thread");
    System.out.println("After name change: " + t);
    try {
      for (int n = 5; n > 0; n--) {
        System.out.println(n);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Main thread interrupted");
    }
  }
}





Get current thread

public class Main extends Thread {
  public void run() {
    for (int i = 0; i < 5; i++) {
      printMyName();
    }
  }
  public void printMyName() {
    System.out.println("The Thread name is " + Thread.currentThread().getName());
  }
  public static void main(String[] args) {
    Main ttsn = new Main();
    ttsn.setName("Created One");
    ttsn.start();
    Thread t2 = currentThread();
    t2.setName("Main One");
    for (int i = 0; i < 5; i++) {
      ttsn.printMyName();
    }
  }
}