Mutithreading- Thread class

Mutithreading- Thread class

The multithreading system of java is built on thread class, its methods and runnable interface.

The execution of threads are encapsulated under Thread. In order to create a new thread, one can either extend the existing thread or implement the runnable interface.

The Thread class implements several class that should be used when working with thread. The methods are listed below

[table “” not found /]

We shall see implementation of above methods.

Example-

getCurrentThread

package com.code2succeed.multithreading;
public class GetCurrentThread {
public static void main(String args[]){
	
	Thread ct=Thread.currentThread();
	System.out.println(ct);
	
}
}

Output

Current running thread is Thread[main,5,main]

In the example above we see that it displays current thread output in a certain ways.

The element at first index location “main” is name of the thread, element at second location “5” is the default priority, and the element at last index location “main” is the name of group to which the thread belongs. A group thread is a data structure which controls the state of collection of threads as a whole.

Let us see implementation of few more methods to understand better.

public class Threadexamples {

	public static void main(String args[]){
		
		//Get the Thread
		Thread ct=Thread.currentThread();
		System.out.println("The current Thread is: "+ct);
		
		//Get the thread name
		System.out.println("Name of Thread is: "+ct.getName());
		
		//Set the thread name
		ct.setName("NewThreadName");
		System.out.println("New name of Thread is: "+ct.getName());
		
		//Get the Thread after changing its name
		System.out.println("The current Thread after altercation is: "+ct);
		
		//Get the priority of thread
		System.out.println("The priority of thread is "+ct.getPriority());
		
		//Check if thread is alive
		System.out.println("Is the thread alive? "+ct.isAlive());
		
		//Suspend the thread for given duration of time. 
		for(int i=3;i>0;i--){
			int t=0;
			t=i*1000;
			try {
				//The thread will be suspended for given duration of time
				System.out.println("Thread is suspend for "+t+" milliseconds");
				ct.sleep(t);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}	
		}		
	}
}

Output

The current Thread is: Thread[main,5,main]
Name of Thread is: main
New name of Thread is: NewThreadName
The current Thread after altercation is: Thread[NewThreadName,5,main]
The priority of thread is 5
Is the thread alive? true
Thread is suspend for 3000 milliseconds
Thread is suspend for 2000 milliseconds
Thread is suspend for 1000 milliseconds

 

Leave a Reply

Your email address will not be published. Required fields are marked *