Friday 28 February 2014

Thread API : Constructors

Thread class provides 8 different types of constructors.

Those are:
1. Thread()
2. Thread(Runnable target)
3. Thread(Runnable target, String name)
4. Thread(String name)
5. Thread(ThreadGroup group, Runnable target)
6. Thread(ThreadGroup group, Runnable target, String name)
7. Thread(ThreadGroup group, Runnable target, String name, long stackSize)
8. Thread(ThreadGroup group, String name)

We will discuss about the first four constructors now. Remaining will be discussed at the time of learning Thread Groups.

1. public Thread()
Creates a Thread object.

2. Thread(Runnable target)
Allocates a new Thread object. Assign the Runnable task to it

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  Thread t2 = new Thread(t1);
  t2.start();
 }
}

Output
Thread name is Thread-0

3. Thread(Runnable target, String name)
Allocates a new Thread object. Assign the Runnable task to it and Assign a name to the thread. When you call the start method, then thread will start executing the run method of the Runnable object

Example
class MyThread implements Runnable{
 public void run(){
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread();
  Thread t2 = new Thread(t1, "My Thread 1");
  t2.start();
 }
}

Output
Thread name is My Thread 1

4. Thread(String name)
Allocates a new Thread object. Assign a name to the thread

Example
class MyThread extends Thread{
 MyThread(String name){
  super(name);
 }

 public void run(){
  System.out.println("Thread name is " + Thread.currentThread().getName());
 }

 public static void main(String args[]){
  MyThread t1 = new MyThread("My Thread 1");
  t1.start();
 } 
}
 
Output
Thread name is My Thread 1

Exploring thread API                                                 Thread running status                                                 Home

No comments:

Post a Comment