Java Tutorial/Thread/Create Thread

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

Create a second thread.

   <source lang="java">

class NewThread implements Runnable {

 Thread t;
 NewThread() {
   t = new Thread(this, "Demo Thread");
   System.out.println("Child thread: " + t);
   t.start(); // Start the thread
 }
 public void run() {
   try {
     for (int i = 5; i > 0; i--) {
       System.out.println("Child Thread: " + i);
       Thread.sleep(500);
     }
   } catch (InterruptedException e) {
     System.out.println("Child interrupted.");
   }
   System.out.println("Exiting child thread.");
 }

} class ThreadDemo {

 public static void main(String args[]) {
   new NewThread();
   try {
     for (int i = 5; i > 0; i--) {
       System.out.println("Main Thread: " + i);
       Thread.sleep(1000);
     }
   } catch (InterruptedException e) {
     System.out.println("Main thread interrupted.");
   }
   System.out.println("Main thread exiting.");
 }

}</source>





Create a second thread by extending Thread

   <source lang="java">

class NewThread extends Thread {

 NewThread() {
   super("Demo Thread");
   System.out.println("Child thread: " + this);
   start(); // Start the thread
 }
 public void run() {
   try {
     for (int i = 5; i > 0; i--) {
       System.out.println("Child Thread: " + i);
       Thread.sleep(500);
     }
   } catch (InterruptedException e) {
     System.out.println("Child interrupted.");
   }
   System.out.println("Exiting child thread.");
 }

} class ExtendThread {

 public static void main(String args[]) {
   new NewThread(); // create a new thread
   try {
     for (int i = 5; i > 0; i--) {
       System.out.println("Main Thread: " + i);
       Thread.sleep(1000);
     }
   } catch (InterruptedException e) {
     System.out.println("Main thread interrupted.");
   }
   System.out.println("Main thread exiting.");
 }

}</source>





Create multiple threads.

   <source lang="java">

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 MultiThreadDemo {

 public static void main(String args[]) {
   new NewThread("One"); // start threads
   new NewThread("Two");
   new NewThread("Three");
   try {
     Thread.sleep(10000);
   } catch (InterruptedException e) {
     System.out.println("Main thread Interrupted");
   }
   System.out.println("Main thread exiting.");
 }

}</source>





Creating a Thread

A thread is a basic processing unit to which an operating system allocates processor time, and more than one thread can be executing code inside a process. (Java 5: A Beginner"s Tutorial by Budi Kurniawan Brainy Software Corp. 2006

Every Java program has at least one thread, the thread that executes the Java program. It is created when you invoke the static main method of your Java class.

There are two ways to create a thread.

  1. Extend the java.lang.Thread class
  2. Implement the java.lang.Runnable interface.
  1. Once you have a Thread object, you call its start method to start the thread.
  2. When a thread is started, its run method is executed.
  3. Once the run method returns or throws an exception, the thread dies and will be garbage-collected.

Every Thread has a state and a Thread can be in one of these six states.

  1. new. A state in which a thread has not been started.
  2. runnable. A state in which a thread is executing.
  3. blocked. A state in which a thread is waiting for a lock to access an object.
  4. waiting. A state in which a thread is waiting indefinitely for another thread to perform an action.
  5. timed__waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action.
  6. terminated. A state in which a thread has exited.

The values that represent these states are encapsulated in the java.lang.Thread.State enum. The members of this enum are NEW, RUNNABLE, BLOCKED, WAITING, TIMED__WAITING, and TERMINATED.


Creating Thread: Deriving a Subclass of Thread

   <source lang="java">

import java.io.IOException; class TryThread extends Thread {

 public TryThread(String firstName, String secondName, long delay) {
   this.firstName = firstName;
   this.secondName = secondName;
   aWhile = delay;
   setDaemon(true);
 }
 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 MainClass {

 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);
   System.out.println("Press Enter when you have had enough...\n");
   first.start();
   second.start();
   third.start();
   try {
     System.in.read();
     System.out.println("Enter pressed...\n");
   } catch (IOException e) {
     System.out.println(e);
   }
   return;
 }

}</source>





Creating Thread Objects: Implementing the run() Method in Runnable interface

   <source lang="java">

import java.io.IOException; class TryThread implements Runnable {

 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);
       Thread.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 MainClass {

 public static void main(String[] args) {
   Thread first = new Thread(new TryThread("A ", "a ", 200L));
   Thread second = new Thread(new TryThread("B ", "b ", 300L));
   Thread third = new Thread(new TryThread("C ", "c ", 500L));
   System.out.println("Press Enter when you have had enough...\n");
   first.start();
   second.start();
   third.start();
   try {
     System.in.read();
     System.out.println("Enter pressed...\n");
   } catch (IOException e) {
     System.out.println(e);
   }
   System.out.println("Ending main()");
   return;
 }

}</source>