Multithreading in Java

Multithreading in Java

Multithreading in java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared memory area. They don’t allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.


Advantages of Java Multithreading

1) It doesn’t block the user because threads are independent and you can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn’t affect other threads if an exception occurs in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:

  • Process-based Multitasking (Multiprocessing)
  • Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

  • Each process has an address in memory. In other words, each process allocates a separate memory area.
  • A process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • A thread is lightweight.
  • Cost of communication between the thread is low.

Note: At least one process is required for each thread.

1). What is Thread in java

A thread is a lightweight sub-process, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn’t affect other threads. It uses a shared memory area.

Java Multithreading

As shown in the above figure, a thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS, and one process can have multiple threads.

Note: At a time one thread is executed only.

Java Thread class

Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.

Java Thread Methods

S.N.Modifier and TypeMethodDescription
1)voidstart()It is used to start the execution of the thread.
2)voidrun()It is used to do an action for a thread.
3)static voidsleep()It sleeps a thread for the specified amount of time.
4)static ThreadcurrentThread()It returns a reference to the currently executing thread object.
5)voidjoin()It waits for a thread to die.
6)intgetPriority()It returns the priority of the thread.
7)voidsetPriority()It changes the priority of the thread.
8)StringgetName()It returns the name of the thread.
9)voidsetName()It changes the name of the thread.
10)longgetId()It returns the id of the thread.
11)booleanisAlive()It tests if the thread is alive.
12)static voidyield()It causes the currently executing thread object to pause and allow other threads to execute temporarily.
13)voidsuspend()It is used to suspend the thread.
14)voidresume()It is used to resume the suspended thread.
15)voidstop()It is used to stop the thread.
16)voiddestroy()It is used to destroy the thread group and all of its subgroups.
17)booleanisDaemon()It tests if the thread is a daemon thread.
18)voidsetDaemon()It marks the thread as daemon or user thread.
19)voidinterrupt()It interrupts the thread.
20)booleanisinterrupted()It tests whether the thread has been interrupted.
21)static booleaninterrupted()It tests whether the current thread has been interrupted.
22)static intactiveCount()It returns the number of active threads in the current thread’s thread group.
23)voidcheckAccess()It determines if the currently running thread has permission to modify the thread.
24)static booleanholdLock()It returns true if and only if the current thread holds the monitor lock on the specified object.
25)static voiddumpStack()It is used to print a stack trace of the current thread to the standard error stream.
26)StackTraceElement[]getStackTrace()It returns an array of stack trace elements representing the stack dump of the thread.
27)static intenumerate()It is used to copy every active thread’s thread group and its subgroup into the specified array.
28)Thread.StategetState()It is used to return the state of the thread.
29)ThreadGroupgetThreadGroup()It is used to return the thread group to which this thread belongs
30)StringtoString()It is used to return a string representation of this thread, including the thread’s name, priority, and thread group.
31)voidnotify()It is used to give the notification for only one thread which is waiting for a particular object.
32)voidnotifyAll()It is used to give the notification to all waiting threads of a particular object.
33)voidsetContextClassLoader()It sets the context ClassLoader for the Thread.
34)ClassLoadergetContextClassLoader()It returns the context ClassLoader for the thread.
35)static Thread.UncaughtExceptionHandlergetDefaultUncaughtExceptionHandler()It returns the default handler invoked when a thread abruptly terminates due to an uncaught exception.
36)static voidsetDefaultUncaughtExceptionHandler()It sets the default handler invoked when a thread abruptly terminates due to an uncaught exception.

2).Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

3).How to create thread

There are two ways to create a thread:

  1. By extending Thread class
  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)

Commonly used methods of Thread class:

  1. public void run(): is used to perform action for a thread.
  2. public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
  3. public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
  4. public void join(): waits for a thread to die.
  5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
  6. public int getPriority(): returns the priority of the thread.
  7. public int setPriority(int priority): changes the priority of the thread.
  8. public String getName(): returns the name of the thread.
  9. public void setName(String name): changes the name of the thread.
  10. public Thread currentThread(): returns the reference of currently executing thread.
  11. public int getId(): returns the id of the thread.
  12. public Thread.State getState(): returns the state of the thread.
  13. public boolean isAlive(): tests if the thread is alive.
  14. public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.
  15. public void suspend(): is used to suspend the thread(depricated).
  16. public void resume(): is used to resume the suspended thread(depricated).
  17. public void stop(): is used to stop the thread(depricated).
  18. public boolean isDaemon(): tests if the thread is a daemon thread.
  19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
  20. public void interrupt(): interrupts the thread.
  21. public boolean isInterrupted(): tests if the thread has been interrupted.
  22. public static boolean interrupted(): tests if the current thread has been interrupted.

Example 1:-Java Thread Example by extending Thread class

class Multithreading1st extends Thread
{
public void run()
{
System.out.println(“thread is running…”);
}
public static void main(String args[])
{
Multithreading1st t1=new Multithreading1st();
t1.start();
}
}

Example 2:-Java Thread Example by implementing Runnable interface

class Multithreading2nd implements Runnable
{
public void run()
{
System.out.println(“thread is running…”);
}

public static void main(String args[])
{
Multithreading2nd m1=new Multithreading2nd();
Thread t1 =new Thread(m1);
t1.start();
}
}

4).Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

  • public static void sleep(long miliseconds)throws InterruptedException
  • public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example 1

class Multithreadingsleep extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingsleep t1=new Multithreadingsleep();
Multithreadingsleep t2=new Multithreadingsleep();
t1.start();
t2.start();
}
}

5).What if we call run() method directly instead start() method?

  • Each thread starts in a separate call stack.
  • Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.

Example 1:-

class Multithreadingrun extends Thread
{
public void run()
{
System.out.println(“running…”);
}
public static void main(String args[])
{
Multithreadingrun t1=new Multithreadingrun();
t1.run();//fine, but does not start a separate call stack
}
}   

Example 2:-Problem if you direct call run() method

class Multithreadingrun1st extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingrun1st t1=new Multithreadingrun1st();
Multithreadingrun1st t2=new Multithreadingrun1st();
t1.run();
t2.run();

6).The join() method

The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.

Syntax:

public void join()throws InterruptedException

public void join(long milliseconds)throws InterruptedException

Example 1:-

class Multithreadingjoin extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingjoin t1=new Multithreadingjoin();
Multithreadingjoin t2=new Multithreadingjoin();
Multithreadingjoin t3=new Multithreadingjoin();
t1.start();
try
{
t1.join();
}
catch(Exception e)
{
System.out.println(e);
}
t2.start();
t3.start();
}
}

Example 2:-

class Multithreadingjoin1st extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String args[])
{
Multithreadingjoin1st t1=new Multithreadingjoin1st ();
Multithreadingjoin1st t2=new Multithreadingjoin1st ();
Multithreadingjoin1st t3=new Multithreadingjoin1st ();
t1.start();
try
{
t1.join(1500);
}
catch(Exception e)
{
System.out.println(e);
}
t2.start();
t3.start();
}
}

7).Naming Thread and Current Thread

Naming Thread

The Thread class provides methods to change and get the name of a thread. By default, each thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the thread by using setName() method. The syntax of setName() and getName() methods are given below:

  1. public String getName(): is used to return the name of a thread.
  2. public void setName(String name): is used to change the name of a thread.

Example 1:-

class Multithreadingname extends Thread
{
public void run()
{
System.out.println(“running…”);
}
public static void main(String args[])
{
Multithreadingname t1=new Multithreadingname();
Multithreadingname t2=new Multithreadingname();
System.out.println(“Name of t1:”+t1.getName());
System.out.println(“Name of t2:”+t2.getName());
t1.start();
t2.start();
t1.setName(“Sonoo Jaiswal”);
System.out.println(“After changing name of t1:”+t1.getName());
}
}

Example 2:-

Current Thread

The currentThread() method returns a reference of currently executing thread.

class Multithreadingname1st extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String args[])
{
Multithreadingname1st t1=new Multithreadingname1st();
Multithreadingname1st t2=new Multithreadingname1st();
t1.start();
t2.start();
}
}

8).Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

3 constants defined in Thread class:

  • public static int MIN_PRIORITY
  • public static int NORM_PRIORITY
  • public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.

Example 1:-

class Multithreadingpriority extends Thread
{
public void run()
{
System.out.println(“running thread name is:”+Thread.currentThread().getName());
System.out.println(“running thread priority is:”+Thread.currentThread().getPriority());

}
public static void main(String args[])
{
Multithreadingpriority m1=new Multithreadingpriority();
Multithreadingpriority m2=new Multithreadingpriority();
m1.setPriority(Thread.MAX_PRIORITY);
m2.setPriority(Thread.MIN_PRIORITY);
m1.start(); 
m2.start();

}
}

Hits: 19

CATEGORIES
TAGS
Share This

COMMENTS

Wordpress (0)
Disqus ( )
%d bloggers like this: