Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Java Multithreading

*Threads. * Thread is also known as lightweight process. Java multithreading allows to process multiple task simultaneously with less overhead than process. Mostly use to monitor session, background synchronization etc.

Content

Processes : These are often application or programs running in their own memory space and runtime resources. In simple term when you run new program with main() method . It is basically a new process and have their own private memory, and resources.

Thread: The path of execution of a process is known as Thread.  A process can have more than one thread. In a simple program with main() method.This program contains a user defined thread with main() method. While with user threads there are system threads like memory management and signal handling.

  • Threads are also known as lightweight processes.
  • A process must contain at least one Thread.
  • All threads inside a process can communicate  each other via shared memory space (Shared variable)

Creating first Java Thread There are two way to create java threads.

    - In both cases we need to override run() method and this method is part of a thread. A thread start from start from starting of run() and ends when run() ends. - To start thread, Thread object needs to be start using *threadObj.start()* which invoke the thread and execute the run method.
  1. Implementing Runnable interface :
public class ThreadExtendingRunnable {
    public static void main(String []args){
        MyThread1 obj1 = new MyThread1("thread1");
        MyThread1 obj2 = new MyThread1("thread2");

        Thread t1 = new Thread(obj1);
        Thread t2 = new Thread(obj2); // you can pass the same object. It allows you to associate single object to multiple threads
        t1.start();
        t2.start();
    }
}

class MyThread1 implements Runnable {
    String str;

    MyThread1(String str){
       this.str = str;
    }
    @Override
    public void run() {
        for(int i=0; i<=5; i++){
            System.out.println(str+" " + i);
        }
    }
}

2.  

Extending 

*Thread class *

public class MyThreadExtendingThread {
    public static void main (String []args){
        MyThread2 t1 = new MyThread2("thread1") ;
        MyThread2 t2 = new MyThread2("thread2") ;

        t1.start();
        t2.start();
    }
}

class MyThread2 extends Thread{
    String str;

    MyThread2(String str){
        this.str = str;
    }
    public void run(){
       for(int i=0; i<=5; i++){
           System.out.println(str+" " + i);
       }
    }
}

 Implementing Runnable vs Extending Thread

:

  • Implementing Runnable allows you to extends another class while, if you extend Thread class you will not able to extends any other class.

  • Extending thread, each thread needs to associate with unique object.
  • Implementing Runnable allows you to associate single object to as many threads you want.
  • Sharing same object to multiple thread also avoids unnecessary object creation and saves memory.

Thread State and Life Cycle

state-machine-example-java-6-thread-states Source: uml-diagram.org

A thread can be one of the following state (java 1.5+)

  • NEW

    : A thread has not started yet.
  • RUNNABLE

    : Thread is running state but it can be in state of waiting.
  • BLOCKED

    :  Thread is waiting to acquire monitor lock to enter into a synchronized block/method after calling Object.wait()
  • WAITING

    : A thread is in waiting state due to calling one of the following methods
    • Object.wait()

      : It causes current thread to wait until it been notified by method notify() or notifyAll().
    • Object.join()

      : Waits for current thread to die.
    • LockSupport.park

      : Disables the current thread for thread scheduling purposes unless the permit is available.
  • TIMED_WAITING

    : Current thread is waits for another thread for specified time to perform the aciton.
    • Thread.sleep (long timeInMilliSecond)

      : Makes current thread to cease the execution for specified time.
    • Object.wait (long timeInMilliSecond) 

      :  Causes current thread to wait for specified time until time elapsed or get notified by notify() or notifyAll().
    • Thread.join (long millis)

      : Current thread waits for specified time to die the thread.
    • LockSupport.parkNanos (long nanoSeconds)

      : Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.
    • LockSupport.parkUntil ()

  • TERMINATED

    : When thread completed its execution.

\<Post in progress to explain thread states>

Daemon Thread Daemon threads are threads to which JVM don't watch to completed or not. So how JVM works, As soon as all user threads finished processing , JVM terminated itself. JVM doesn't wait to finish daemon threads. Garbage collector and other housekeeping threads are inbuild daemon threads.

  • User created threads are non-daemon by default, since it's created by main() thread which is by default a non-daemon and newly created thread inherit daemon property from the thread it was created.
  • To set a user created thread as daemon, you need to set by

    Thread.setDaemon(true)

    (Make sure you set a daemon before calling

    start()

    ).

Example: Daemon Thread

public class DaemonTest {
    public static void main(String []args){
        DaemonObject deamonObj = new DaemonObject(1000, "daemonThread");
        DaemonObject notDaemonObj = new DaemonObject(500, "notDaemonThread");

        Thread t1 = new Thread(deamonObj);
        Thread t2 = new Thread(notDaemonObj);

        t1.setDaemon(true);
        t1.start();
        t2.start();
    }
}

class DaemonObject implements Runnable{
    int sleepTime;
    String threadname;
    DaemonObject(int sleepTime, String threadname){
       this.sleepTime = sleepTime;
       this.threadname = threadname;
    }
    @Override
    public void run() {

       for(int i=0; i < 5; i++){
           System.out.println(threadname+ " " + i);
           try {
               Thread.sleep(sleepTime);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }

    }
}
----------
Output will be like: 
----------
daemonThread 0
notDaemonThread 0
notDaemonThread 1
daemonThread 1
notDaemonThread 2
notDaemonThread 3
daemonThread 2
notDaemonThread 4

Process finished with exit code 0

Notice, thread marked as daemon thread didn't completed its execution, because JVM only waited for non-daemon thread and as soon as it completed, JVM also terminated.

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy