Creating and Executing Threads in Java

You can create threads directly instantiating a Thread class or using the newer better and safer concurrency package features such as Executors.

Though it is not preferred to create threads directly in new code, learning to create threads directly working with Thread class helps to understand basics well.

We can create a Thread by

  • extending the Thread class or

  • implementing Runnable interface and passing it to a Thread class constructor.

Both the Thread class and the Runnable interface contains a method called run; you have to override it.

When we call the start() method of the Thread class, the run() method is called as a separate thread of execution.

You also can call the run method directly, but then, it will be executed like any other method, not as a separate thread of execusion.

The Thread class also defines several methods to query and manage a thread like getName(), getPriority(), isAlive(), join(), run(), sleep(),start() etc., but we rarely need to override them and usually override only the run method.

Unless you have a reason, like override any of those extra Thread class methods, you should implement Runnable compared to extending Thread class as it gives you more flexibility as, in Java, you can extend only one class, but you can implement any number of interfaces along with extending a class.

 

Syntax and Examples

Syntax:

The signature of run() method is:

public void run(){…}

 

Example 1: Extending Thread class

public class MyThread extends Thread {

         public void run()

         {

                 for(int i=0;i<10;i++)

                 {

                          System.out.println(i);

                          try {

                                  Thread.sleep(500);

                          } catch (InterruptedException e) {

                                  e.printStackTrace();

                          }

                 }

         }

}

You can create a Thread object as:

Thread t = new MyThread();

 

Example 2: Implementing Runnable

public class MyRunnable implements Runnable {

         public void run()

         {

                 for(int i=0;i<10;i++)

                 {

                          System.out.println(i);

                          try {

                                  Thread.sleep(1);

                          } catch (InterruptedException e) {

                                  e.printStackTrace();

                          }

                 }

         }

}

you can create a Thread object as:

Thread t = new Thread(new MyRunnable());

Here we pass the Runnable interface implementation on to the Thread constructor.

Next we will see how to start a thread of execution.

 

Starting a Thread of Execution

A thread of execution can be started by calling start() on a thread object as:

t.start();

When you call start() method on a thread object, its run() method will be executed as a new thread.

You can even call the run method directly, though not recommended, this will not run as a separate thread, but just like any other method call from the calling thread as part of the calling thread.

 

Completing thread example

To demonstrate separate thread of execuion in parallel, we will create three thread objects and then start these three thread objects as separate path of execution. We will write a simple loop that prints from 1 to 10 and we can see that these three loops are executed in parallel, not serial in the order we called start. 

Note however that, though these are three separate threads and can execute in parallel, it is upto the scheduler to decide which thread to run when these three are in runnable state; and it can even run them one by one if all of them are in runnable state. So we will send each thread to a small blocked state using Thread.sleep() so that the scheduler will have to then select from other two threads to execute. The static method Thread.sleep() causes the thread to suspend execution for a specified time. Since Thread.sleep can throw InterruptedException, you need to handle it using a try catch. 

We will use the Thread classes created  previously:

public class SimpleThreadExample {

         public static void main(String[] args) {

                 MyThread t1 = new MyThread();

                 MyThread t2 = new MyThread();

                 Thread t3 = new Thread(new MyRunnable());

                 t1.start();

                 t2.start();

                 t3.start();

         }

}

Try the example and understand it well, before moving any further learning about threads.

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)