Create Thread in Java

Category: Java   Tags: Java, Java Thread

A multithreaded program allows you to run two or more parts run concurrently. Each part of such a program is called a thread. Each thread is a separate path of execution.

Difference Between Thread and Process

A thread runs in a shared memory space while a process runs in a separate memory space. A process has its own run-time resources.

Creating a new thread requires fewer resources than creating a new process. Threads are sometimes called lightweight processes. A Java program start with one thread called main thread.

Threads exist within a process and every process has at least one thread. Threads share the process's resources, like memory and open files. In Java every program has at least one thread. In Java you can create processes using ProcessBuilder object.

Creating a Java Thread

Java defines two ways of creating a thread:

  • Implement Runnable interface
  • Extend Thread class

Implementing Runnable

Here is how you can create a Java thread by implementing Runnable interface:

Implement the Runnable: Create a class that implements the Runnable interface. For example class MyThread implements Runnable {}

Override the method run(): Code defined inside run() constitutes the new thread. This method is the entry point for another thread within your program. Thread will end once this method returns. It is declared like this:

                            public void run() {}
                          

Create an instance of Thread class: Thread class defines several constructors. The one that we will use is shown here:

                            Thread(Runnable threadObject, String threadName)
                          

threadObject is an instance of a class that implements the Runnable interface. This defines where thread execution will begin. threadName is the new thread name. Here is one example of thread creation:

RunnableThreadExample.java

                            package com.tutorial.javabasic;

                            // Create a second thread
                            class MyThread implements Runnable {
                                Thread thread;

                                public MyThread() {
                                    // Create a new, second thread
                                    thread = new Thread(this, "This is my thread");

                                    // Start the thread
                                    thread.start();
                                }

                                // Entry point for the second thread
                                @Override
                                public void run() {
                                    System.out.println("Child thread: " + thread.getName());
                                }
                            }

                            public class RunnableThreadExample {
                                public static void main(String s[]) {
                                    System.out.println("Main thread");
                                    new MyThread();
                                }
                            }
                        

Output:

                            Main Thread
                            Child thread: This is my thread
                          

Every Java program start with a single thread called Main Thread. This thread start just after your program begins. All child threads are created from this main thread. A main thread should be the last thread to finish as various shutdown activities are performed inside this.

Here passing this to Thread constructor says that you want the new thread to call the run() method on this object.

thread.start(); start a new thread by calling run() method. Inside run(), you will define the code that constitutes the new thread

Extending Thread

Another way of creating a thread in Java is to create a new class that extends Thread class. The extending class must override the run() method, the entry point for the new thread. It must also call start() to begin execution of the new thread.

ThreadExtendsExample.java

                            package com.tutorial.javabasic;

                            // Create a second thread
                            class MyThread extends Thread {

                                public MyThread() {
                                    super("My Thread!");

                                    // Start the thread
                                    start();
                                }

                                // Entry point for the second thread
                                @Override
                                public void run() {
                                    System.out.println("Child thread: " + this.getName());
                                }
                            }

                            public class ThreadExtendsExample {
                                public static void main(String s[]) {
                                    System.out.println("Main thread");
                                    new MyThread();
                                }
                            }
                        

Output:

                            Main Thread
                            Child thread: My Thread!
                          

super("My Thread!") calls the public Thread(String threadName) constructor of Thread class. threadName is the name of the thread.

Choosing an Approach

So you saw that there are two ways to create a thread in Java. Now the question is which one to choose? In java you can extend only one class but you can implement more than once interface. Therefore, if you extend Thread, you won't be able to extend any other classes. If you implement Runnable, you can extend other class.

Because of these limitation implementing Runnable is the recommended way of creating a thread in Java.