Java Thread(Runnable target, String name) Constructor

Syntax

Thread(Runnable target, String name) constructor from Thread has the following syntax.

public Thread(Runnable target,  String name)

Example

In the following code shows how to use Thread.Thread(Runnable target, String name) constructor.


/*from   w  ww.  java2s.  co m*/
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 Main {
  public static void main(String[] args) {
    Thread first = new Thread(new TryThread("A ", "a ", 200L),"name");
    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;
  }
}




















Home »
  Java Tutorial »
    java.lang »




Boolean
Byte
Character
Class
Double
Enum
Float
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runnable
Runtime
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable