Thread Java

Multithreading:

Multithreading refers to a type of multitasking based upon threads. Context switching in case of multi-threading is done in-between threads instead of processes.

Thread:

A thread is used to execute multiple activities or tasks with-in a single process. It refers to a lightweight process. Thread uses process’s memory area i.e. execution environment. Multiple threads can share the same memory, files and per-process state with-in the process. According to thread model, threads can have Program counter, Registers, Stack, and State as per thread.

Note: Every thread has a activity or task associated with it and it can not exist without process.

Use of Threads:

  • To execute multiple task simultaneously e.g. writing on notepad and event handling.
  • Full CPU utilization (multiprocessor systems).
  • Increase the performance by reducing processing time with the help of simultaneous execution of multiple threads.
  • Provides the facility to server the multiple users at the same time.

Java Thread Model

Thread States:

  • New
  • Runnable
  • Running
  • Non-Runnable
    • Timed waiting
    • Waiting
    • Blocked
  • Terminated.

Ways to create thread in java

A thread in java can be created either by implementing Runnable interface or by extending Thread class.

  • Implementing Runnable interface (java.lang.Runnable)
  • Extending Thread class (java.lang.Thread)

 

Thread example by implementing Runnable Interface:

Runanable interface contains only one method whose definition have to be provided by our implementation class.

Steps to create a thread when we implement Runnable Interface

  • Create Object of Runnable class.
  • Pass Runnable class object in Thread class constructor while creating Thread class object.
  • Call start() method on thread object which in turn will call run() method to perform a specific task.
public void run();

Example

public class Main extends Thread {
    @Override
    public void run() {
        System.out.println("Inside Thread: " + Thread.currentThread().getName());
    }
 
    public static void main(String[] args) {
        System.out.println("Inside Thread: " + Thread.currentThread().getName());
 
        //Creating Thread
        Thread thread = new Main();
 
        System.out.println("Start Thread");
        thread.start();
    }
 
}

Output

Inside Thread: main
Start Thread
Inside Thread: Thread-0

 

Thread example by extending Thread Class:

Steps to create a thread when we extend Thread Class

  • Create Object of Custom Thread class (Class which extends Thread class).
  • Call start() method on custom thread class object which in turn will call run() method to perform a specific activity or task.

Commonly used methods of Thread Class

Method Signature Method Description
String getName() It is used to retrieve the name of running thread in the current context.
void start() It is used to start a new thread of execution by calling run() method.
void run() It represents the thread entry point.
void sleep(int sleeptime) It is used to suspend the thread for specified time duration.
void yield() It is used to pause the execution of current thread temporarily and allow other threads to execute.
void join() It is used to queue up a thread in execution. When join() method is called on specific thread (current thread) then that thread will wait till calling thread completes its execution.
boolean isAlive() This method is used to determine if specified thread is alive or dead.

  Example

public class Main implements Runnable {
     @Override
    public void run() {
        System.out.println("Inside Thread: " + Thread.currentThread().getName());
    }
 
    public static void main(String[] args) {
        System.out.println("Inside Thread: " + Thread.currentThread().getName());
 
        //Create Runnable
        Runnable runnable = new Main();
 
        //Create thread
        Thread thread = new Thread(runnable);
 
        System.out.println("Start Thread");
        thread.start();
    }
}

Output

Inside Thread: main
Start Thread
Inside Thread: Thread-0

 

Creating Multiple Threads Example:

class TestThread implements Runnable {
    String threadNme;
    Thread thread;
    TestThread (String threadNme){
        this.threadNme = threadNme; 
        thread = new Thread(this, threadNme);
        System.out.println("New thread created: " + threadNme);
        thread.start();
    }
 
    public void run() {
    try {
        for(int i = 4; i > 0; i--) {
            System.out.println(threadNme + ": " + i);
            Thread.sleep(1500);
        }
    }catch (InterruptedException e) {
        System.out.println(threadNme + " is interrupted");
    }
        System.out.println(threadNme + " is exiting.");
    }
}
 
public class Main {
    public static void main(String args[]) {
        new TestThread("TestThread1");
        new TestThread("TestThread2");
        new TestThread("TestThread3");
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            System.out.println("Main thread is Interrupted");
        }
        System.out.println("Main thread is exiting.");
    }
}

Output

New thread created: TestThread1 
New thread created: TestThread2
TestThread1: 4 
New thread created: TestThread3 
TestThread3: 4 
TestThread2: 4 
TestThread1: 3
TestThread3: 3  
TestThread2: 3  
TestThread1: 2
TestThread3: 2
TestThread2: 2
TestThread1: 1
TestThread2: 1
TestThread3: 1
TestThread1 is exiting.
TestThread2 is exiting.
TestThread3 is exiting.
Main thread is exiting.

Thread example using Anonymous class

public class Main {
 
    public static void main(String[] args) {
        System.out.println("Inside Thread: " + Thread.currentThread().getName());
 
        //Create Runnable as Anonymous class
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("Inside Thread: " + Thread.currentThread().getName());
            }
        };
 
        //Create thread
        Thread thread = new Thread(runnable);
 
        System.out.println("Start Thread");
        thread.start();
    }
 
}

Output

Inside Thread: main
Start Thread
Inside Thread: Thread-0

Thread example using Java 8, lambda expression

public class Main {
 
    public static void main(String[] args) {
        System.out.println("Inside Thread: " + Thread.currentThread().getName());
 
        //Create Runnable using lambda expression
        Runnable runnable = () -> {
            System.out.println("Inside Thread: " + Thread.currentThread().getName());
        };
 
        //Create thread
        Thread thread = new Thread(runnable);
 
        System.out.println("Start Thread");
        thread.start();
    }
 
}

Output

Inside Thread: main
Start Thread
Inside Thread: Thread-0

Which one to use, Runnable or Thread

We should us Runnable, it has mainly 2 advantages over Thread.

  • If we extends Thread class, all thread class methods will be inherited which results into overhead. In case of Runnable interface there will be only one method that is run.
  • Another reason of Runnable preference is Multiple inheritance. As we know that java does not support multiple inheritance in case of classes, so when we extends the Thread class then no another class can be extended.

Java interview questions on multithreading

Please follow and like us:
Content Protection by DMCA.com