Java Thread Class

Java contains inbuilt Class Thread under the package of java.lang, This class helps to create/span a new Thread with in the Java application.

Commonly Used Methods

Thread Class start method Example

public class CreationOfThread extends Thread {

	public static void main(String[] args) {
		Thread thread=new CreationOfThread();
		thread.start();
	}
	
	public void run()
	{
		System.out.println("New thread started Running");
	}

}

Thread Class sleep method Example

public class CreationOfThread extends Thread {

	public static void main(String[] args) {
		Thread thread=new CreationOfThread();
		thread.start();
	}
	
	public void run()
	{
		try {
		System.out.println("Going For a Sleep");
		Thread.sleep(1000);
		System.out.println("Woken Up!!!!!!");
		 }
		 catch(Exception e) {
		 e.printStackTrace();
		 }
	}

}

Thread Class join method Example

public class CreationOfThread extends Thread {

	public static void main(String[] args)throws Exception {
		Thread thread=new CreationOfThread();
		thread.start();
		thread.join();
	}
	
	public void run()
	{
		try {
		System.out.println("Going For a Sleep");
		Thread.sleep(1000);
		System.out.println("Woken Up!!!!!!");
		 }
		 catch(Exception e) {
		 e.printStackTrace();
		 }
	}

}

Thread Class interrupt method Example

public class CreationOfThread extends Thread {

	public static void main(String[] args) {
		Thread thread=new CreationOfThread();
		thread.start();
		thread.interrupt();
	}
	
	public void run()
	{
		try {
		System.out.println("Going For a Sleep");
		Thread.sleep(1000);
		System.out.println("Woken Up!!!!!!");
		 }
		 catch(Exception e) {
		 e.printStackTrace();
		 }
	}

}

Thread Class isAlive method Example

public class CreationOfThread extends Thread {

	public static void main(String[] args) {
		Thread thread=new CreationOfThread();
		thread.start();
	}
	
	public void run()
	{
		try {
		System.out.println("Going For a Sleep");
		Thread.sleep(1000);
		System.out.println("Woken Up!!!!!!");
		System.out.println("isAlive() :"+isAlive());
		 }
		 catch(Exception e) {
		 e.printStackTrace();
		 }
	}

}