Java Thread

Java Thread

Java Thread

We know about Java Thread and what are different states of a java thread. In this tutorial, we will implement thread in our java program. There are more than one way of creating a new thread in java. We will discuss all of them and some important methods of a java thread.


How to create a thread in java


There are two ways of creating a new thread in java, you can use either of one way. We will discuss each of them and which one is good to use.

  1. Extending java.lang.Thread class.
  2. Implementing java.lang.Runnable interface.

Java Thread



You can create a new thread by simply extending Thread class with your class or implementing Runnable interface. Let’s discuss each of them.


The java.lang.Thread class


You can declare your class to be sub class of Thread class. Sub class which is extending Thread class must override it’s run() method. After that, you can create an instance of the sub class to start a new thread in java.

The run() method is the main key here, whatever code you want to execute should come inside in this run method. When thread will start it’s execution, it will look for the run() method and will execute whatever code inside it.

Simple Example

class ThreadExample extends Thread {
 
 public void run() {
 
   try {
     for(int i=1; i<=10; i++) {
       System.out.println("Number : " + i);
       Thread.sleep(1000);
     }
   } catch (Exception e) {
       e.printStackTrace();
   }
 
 }

 public static void main(String[] args) { 
 
     ThreadExample t = new ThreadExample();
     t.start();
 }

}

Output :
Number : 1
Number : 2
Number : 3
Number : 4
Number : 5
Number : 6
Number : 7
Number : 8
Number : 9
Number : 10


What’s happening above

  1. We have a new class ThreadExample which is extending the Thread class.
  2. Thread class has run() method which should be overridden in the base class.
  3. The run() method is overridden and we are trying to print number from 1 to 10.
  4. Thread class has static sleep() method which is used to stop execution of thread for the given time.
  5. New instance has been created and start() method invoked.
  6. After start() method, thread is alive and ready to execute.
  7. Whatever code written inside run() method will be executed.

Some Important overloaded constructor of Thread class

Thread class has some overloaded methods which is used to instantiate a thread, you can choose any constructor to create a new thread in java programming. So let’s see them.

Thread Constructors
Thread()
Creates a new thread object.
Thread(Runnable target)
Creates a new thread as per the passed runnable target.
Thread(Runnable target, String name)
You can also use runnable as parameter and thread name to create a new thread object.
Thread(String name)
You can provide a name to the newly created thread.
Thread(ThreadGroup group, Runnable target)
You can add the particular thread to the thread group.
Thread(ThreadGroup group, String name)
Used to add particular thread to the thread group and name the thread.

Some important methods of Thread class


Return type and it’s modifier Name of the method and description
static int activeCount()
Returns the number of active threads in the current thread group.
static Thread currentThread()
Method is used to get the reference of the currently executing thread.
long getId()
Method can be used to get the unique reference id of the current executing thread object.
String getName()
Returns the name of the thread.
int getPriority()
Returns the priority of the currently executing thread.
Thread.State getState()
You can get the current of the thread object.
void interrupt()
If you want to interrupt any executing thread, this method is useful.
static boolean interrupted()
You can also check whether the current thread has been interrupted or not.
boolean isAlive()
To check whether the thread is alive or not.
boolean isDaemon()
Check whether the current thread is Daemon thread or not. Daemon threads are those threads which runs in the background.
void join()
This method is used to execute the threads in the sequence which is helpful if you want to make sure the second thread does not execute before first thread completes it’s execution. So it waits for this thread to die.
void join(long millis)
This method is used to execute the threads in the sequence which is helpful if you want to make sure the second thread does not execute before first thread completes it’s execution. So it waits for this thread to die for the given mili seconds.
void run()
Run method is used to execute the code and perform what ever action is required.
void setDaemon(boolean on)
Set a thread as daemon thread.
void setName(String name)
Set the name of the thread.
void setPriority(int newPriority)
Method is used to set the priority of the thread so that Thread Scheduler can decide which thread to execute first.
static void sleep(long millis)
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
static void sleep(long millis, int nanos)
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.
void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
static void yield()
A hint to the scheduler that the current thread is willing to yield its current use of a processor.

Another good example


class ThreadExample extends Thread {
 
 public void run() {
 
   System.out.println("Thread (" + this.getName() + ") has begin it's execution.");
 
   if(this.isDaemon()) {
     System.out.println("This thread is daemon thread.");
   }
 
   System.out.println("Thead State : " + this.getState());
 
   try {
     for(int i=1; i<=10; i++) {
       System.out.println("Number : " + i);
       Thread.sleep(1000);
     }
   } catch (Exception e) {
       e.printStackTrace();
   }
 
   System.out.println("Thread count : " + this.activeCount());
 }

}

public class Test {

 public static void main(String[] args) { 
 
   ThreadExample t = new ThreadExample();
 
   t.setName("Thread Examples Thread");
   t.setDaemon(true);
 
   t.start();
 }

}
Output:
Thread (Thread Examples Thread) has begin it's execution.
This thread is daemon thread.
Thead State : RUNNABLE
Number : 1

The java.lang.Runnable interface

 

The Runnable interface can be implemented by any class. A class which is implementing Runnable interface does not need to be the sub class of Thread class. An instance of the class which is implementing the Runnable interface is passed to the Thread class as the target. 

The Runnable interface is useful if you just want to execute some code inside run() method for parallel execution and does not need any other methods of Thread class. Because if you extend Thread class, all methods of Thread class will be inheriting to your class which you may not need. This will cause additional overhead. You can remove this overhead by implementing Runnable interface.

A simple example

class ThreadExample implements Runnable {
 
 public void run() {
 
   try {
     for(int i=1; i<=10; i++) {
       System.out.println("Number : " + i);
       Thread.sleep(1000);
     }
   } catch (Exception e) {
       e.printStackTrace();
   }
 }

}

public class Test {

 public static void main(String[] args) { 
 
   Thread t = new Thread(new ThreadExample());
   t.start();
 }

}
Output:
Number : 1
Number : 2
Number : 3
Number : 4
Number : 5
Number : 6
Number : 7
Number : 8
Number : 9
Number : 10



As you can see above, the run() method is given to you. Just write what you want to execute and it will be given to the thread to execute it further. No any other method is given to you, if you try to call getName(), setName() or any other method you will receive error because they are not the part of Runnable interface.

You just need to implement the Runnable interface with your class. Create the instance of this class and pass it to the Thread class as target object. Thread class will take it forward for further execution.


Methods of Runnable Interface

The Runnable interface has one and only one so let’s see it.

void run()

When an object implementing interface Runnable is used to create a thread, starting the thread causes the object’s run method to be called in that separately executing thread.

The general contract of the method run is that it may take any action whatsoever.

 

Related Post

Leave a Reply

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