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
- start()
which helps to create a new thread.
- sleep()
which helps to stop the thread execution for certain amount of time.
- join()
which helps to wait current execution thread until the completion of other thread.
- interrupt()
which helps to interrupt the execution of a specific thread.
- isAlive()
which helps to check whether thread is currently running or completed the execution.
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(); } } }