Multithreading in Java- An Introduction
In Java, Multithreading refers to a strategy of executing two or extra threads concurrently for optimum utilization of the CPU. A thread in Java is a light-weight course of requiring fewer assets to create and share the method assets.
Multithreading and Multiprocessing are used for multitasking in Java, however we choose multithreading over multiprocessing. It is because the threads use a shared reminiscence space which helps to avoid wasting reminiscence, and likewise, the content-switching between the threads is a bit quicker than the method.
Few extra benefits of Multithreading are:
- Multithreading saves time as you’ll be able to carry out a number of operations collectively.
- The threads are unbiased, so it doesn’t block the person to carry out a number of operations on the identical time and likewise, if an exception happens in a single thread, it doesn’t have an effect on different threads.
Life Cycle of a Thread
There are 5 states a thread has to undergo in its life cycle. This life cycle is managed by JVM (Java Digital Machine). These states are:
- New
- Runnable
- Working
- Non-Runnable (Blocked)
- Terminated
1. New
On this state, a brand new thread begins its life cycle. That is additionally known as a born thread. The thread is within the new state should you create an occasion of Thread class however earlier than the invocation of the begin() technique.
2. Runnable
A thread turns into runnable after a newly born thread is began. On this state, a thread can be executing its activity.
3. Working
When the thread scheduler selects the thread then, that thread can be in a working state.
4. Non-Runnable (Blocked)
The thread continues to be alive on this state, however at the moment, it isn’t eligible to run.
5. Terminated
A thread is terminated because of the following causes:
- Both its run() technique exists usually, i.e., the thread’s code has executed this system.
- Or as a consequence of some uncommon errors like segmentation fault or an unhandled exception.
A thread that’s in a terminated state doesn’t devour ant cycle of the CPU.
Java Thread Class
The Java Thread class gives strategies and constructors to create and carry out operations on a thread. The Java thread class extends the Object class and implements the Runnable interface.
Java Thread Strategies
These are the strategies which can be obtainable within the Thread class:
1. public void begin()
It begins the execution of the thread after which calls the run() on this Thread object.
Instance:
{
public void run()
{
System.out.println("Thread is working...");
}
public static void foremost(String args[])
{
StartExp1 thread1=new StartExp1();
thread1.begin();
}
}
Output:
Thread is working…
2. public void run()
This thread is used to do an motion for a thread. The run() technique is instantiated if the thread was constructed utilizing a separate Runnable object.
Instance:
public class RunExp1 implements Runnable
{
public void run()
{
System.out.println("Thread is working...");
}
public static void foremost(String args[])
{
RunExp1 r1=new RunExp1();
Thread thread1 =new Thread(r1);
thread1.begin();
}
}
Output:
Thread is working…
3. public static void sleep()
This blocks the at the moment working thread for the desired period of time.
Instance:
public class SleepExp1 extends Thread
{
public void run()
{
for(int i=1;i<5;i++)
{
strive
{
Thread.sleep(500);
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void foremost(String args[])
{
SleepExp1 thread1=new SleepExp1();
SleepExp1 thread2=new SleepExp1();
thread1.begin();
thread2.begin();
}
}
Output:
1
1
2
2
3
3
4
4
4. public static Thread currentThread()
It returns a reference to the at the moment working thread.
Instance:
public class CurrentThreadExp extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void foremost(String args[])
{
CurrentThreadExp thread1=new CurrentThreadExp();
CurrentThreadExp thread2=new CurrentThreadExp();
thread1.begin();
thread2.begin();
}
}
Output:
Thread-0
Thread-1
5. public void be a part of()
It causes the present thread to dam till the second thread terminates or the desired quantity of milliseconds passes.
Instance:
public class JoinExample1 extends Thread
{
public void run()
{
for(int i=1; i<=4; i++)
{
strive
{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void foremost(String args[])
{
JoinExample1 thread1 = new JoinExample1();
JoinExample1 thread2 = new JoinExample1();
JoinExample1 thread3 = new JoinExample1();
thread1.begin();
strive
{
thread1.be a part of();
}catch(Exception e){System.out.println(e);}
thread2.begin();
thread3.begin();
}
}
Output:
1
2
3
4
1
1
2
2
3
3
4
4
6. public closing int getPriority()
It’s used to test the precedence of the thread. When a thread is created, some precedence is assigned to it. This precedence is assigned both by the JVM or by the programmer explicitly whereas creating the thread.
Instance:
public class JavaGetPriorityExp extends Thread
{
public void run()
{
System.out.println("working thread identify is:"+Thread.currentThread().getName());
}
public static void foremost(String args[])
{
JavaGetPriorityExp t1 = new JavaGetPriorityExp();
JavaGetPriorityExp t2 = new JavaGetPriorityExp();
System.out.println("t1 thread precedence : " + t1.getPriority());
System.out.println("t2 thread precedence : " + t2.getPriority());
t1.begin();
t2.begin();
}
}
Output:
t1 thread precedence : 5
t2 thread precedence : 5
working thread identify is:Thread-0
working thread identify is:Thread-1
7. public closing void setPriority()
This technique is used to alter the precedence of the thread. The precedence of each thread is represented by the integer quantity from 1 to 10. The default precedence of a thread is 5.
Instance:
public class JavaSetPriorityExp1 extends Thread
{
public void run()
{
System.out.println("Precedence of thread is: "+Thread.currentThread().getPriority());
}
public static void foremost(String args[])
{
JavaSetPriorityExp1 t1=new JavaSetPriorityExp1();
t1.setPriority(Thread.MAX_PRIORITY);
t1.begin();
}
}
Output:
Precedence of thread is: 10
8. public closing String getName()
This technique of thread class is used to return the identify of the thread. We can not override this technique in our program, as this technique is closing.
Instance:
public class GetNameExample extends Thread
{
public void run()
{
System.out.println("Thread is working...");
}
public static void foremost(String args[])
{
// creating two threads
GetNameExample thread1=new GetNameExample();
GetNameExample thread2=new GetNameExample();
System.out.println("Identify of thread1: "+ thread1.getName());
System.out.println("Identify of thread2: "+thread2.getName());
thread1.begin();
thread2.begin();
}
}
Output:
Identify of thread1: Thread-0
Identify of thread2: Thread-1
Thread is working…
Thread is working…
9. public closing void setName()
This technique adjustments the identify of the thread.
Instance:
public class SetNameExample extends Thread
{
public void run()
{
System.out.println("working...");
}
public static void foremost(String args[])
{
SetNameExample thread1=new SetNameExample();
SetNameExample thread2=new SetNameExample();
thread1.begin();
thread2.begin();
thread1.setName("Kadamb Sachdeva");
thread2.setName("Nice studying");
System.out.println("After altering identify of thread1: "+thread1.getName());
System.out.println("After altering identify of thread2: "+thread2.getName());
}
}
Output:
After altering identify of thread1: Kadamb Sachdeva
After altering identify of thread2: Nice Studying
working…
working…
10. public lengthy getId()
It returns the identifier of the thread. The thread ID is a quantity generated when the thread was created. This ID can’t be modified throughout its lifetime. However when the thread is terminated, the ID might be reused.
Instance:
public class GetIdExample extends Thread
{
public void run()
{
System.out.println("working...");
}
public static void foremost(String args[])
{
GetIdExample thread1=new GetIdExample();
System.out.println("Identify of thread1: "+thread1.getName());
System.out.println("Id of thread1: "+thread1.getId());
thread1.begin();
}
}
Output:
Identify of thread1: Thread-0
Id of thread1: 21
working…
11. public closing boolean isAlive()
This technique checks if the thread is alive. A thread is within the alive state if the beginning() technique of thread class has been known as and the thread has not but died.
Instance:
public class JavaIsAliveExp extends Thread
{
public void run()
{
strive
{
Thread.sleep(300);
System.out.println("is run() technique isAlive "+Thread.currentThread().isAlive());
}
catch (InterruptedException ie) {
}
}
public static void foremost(String[] args)
{
JavaIsAliveExp thread1 = new JavaIsAliveExp();
System.out.println("earlier than beginning thread isAlive: "+thread1.isAlive());
thread1.begin();
System.out.println("after beginning thread isAlive: "+thread1.isAlive());
}
}
Output:
earlier than beginning thread isAlive: false
after beginning thread isAlive: true
is run() technique isAlive true
12. public static void yield()
This technique pauses the execution of the present thread to execute different threads quickly.
Instance:
public class JavaYieldExp extends Thread
{
public void run()
{
for (int i=0; i<3 ; i++)
System.out.println(Thread.currentThread().getName() + " in management");
}
public static void foremost(String[]args)
{
JavaYieldExp thread1 = new JavaYieldExp();
JavaYieldExp thread2 = new JavaYieldExp();
thread1.begin();
thread2.begin();
for (int i=0; i<3; i++)
{
thread1.yield();
System.out.println(Thread.currentThread().getName() + " in management");
}
}
}
Output:
foremost in management
foremost in management
foremost in management
Thread-0 in management
Thread-0 in management
Thread-0 in management
Thread-1 in management
Thread-1 in management
Thread-1 in management
13. public closing void droop()
This technique is used to droop the at the moment working thread quickly. Utilizing the resume() technique, you’ll be able to resume the suspended thread.
Instance:
public class JavaSuspendExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
strive
{
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void foremost(String args[])
{
JavaSuspendExp thread1=new JavaSuspendExp ();
JavaSuspendExp thread2=new JavaSuspendExp ();
JavaSuspendExp thread3=new JavaSuspendExp ();
thread1.begin();
thread2.begin();
thread2.droop();
thread3.begin();
}
}
Output:
Thread-0
1
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4
14. public closing void resume()
This technique is used to renew the suspended thread. It is just used with the droop() technique.
Instance:
public class JavaResumeExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
strive
{
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void foremost(String args[])
{
JavaResumeExp thread1=new JavaResumeExp ();
JavaResumeExp thread2=new JavaResumeExp ();
JavaResumeExp thread3=new JavaResumeExp ();
thread1.begin();
thread2.begin();
thread2.droop();
thread3.begin();
thread2.resume();
}
}
Output:
Thread-0
1
Thread-2
1
Thread-1
1
Thread-0
2
Thread-2
2
Thread-1
2
Thread-0
3
Thread-2
3
Thread-1
3
Thread-0
4
Thread-2
4
Thread-1
4
15. public closing void cease()
Because the identify suggests, this technique is used to cease the at the moment working thread. Keep in mind, as soon as the thread execution is stopped, it can’t be restarted.
Instance:
public class JavaStopExp extends Thread
{
public void run()
{
for(int i=1; i<5; i++)
{
strive
{
sleep(500);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void foremost(String args[])
{
JavaStopExp thread1=new JavaStopExp ();
JavaStopExp thread2=new JavaStopExp ();
JavaStopExp thread3=new JavaStopExp ();
thread1.begin();
thread2.begin();
thread3.cease();
System.out.println("Thread thread3 is stopped");
}
}
Output:
16. public void destroy()
This thread technique destroys the thread group in addition to its subgroups.
Instance:
public class JavaDestroyExp extends Thread
{
JavaDestroyExp(String threadname, ThreadGroup tg)
{
tremendous(tg, threadname);
begin();
}
public void run()
{
for (int i = 0; i < 2; i++)
{
strive
{
Thread.sleep(10);
}
catch (InterruptedException ex) {
System.out.println("Exception encounterted");}
}
System.out.println(Thread.currentThread().getName() +
" completed executing");
}
public static void foremost(String arg[]) throws InterruptedException, SecurityException
{
ThreadGroup g1 = new ThreadGroup("Mum or dad thread");
ThreadGroup g2 = new ThreadGroup(g1, "little one thread");
JavaDestroyExp thread1 = new JavaDestroyExp("Thread-1", g1);
JavaDestroyExp thread2 = new JavaDestroyExp("Thread-2", g1);
thread1.be a part of();
thread2.be a part of();
g2.destroy();
System.out.println(g2.getName() + " destroyed");
g1.destroy();
System.out.println(g1.getName() + " destroyed");
}
}
Output:
Thread-1 completed executing
Thread-2 completed executing
little one thread destroyed
Mum or dad thread destroyed
17. public closing boolean isDaemon()
This thread technique will test if the thread is a daemon thread or not. If it’s a daemon thread, then it can return true else, it can return false.
For individuals who don’t find out about a daemon thread, a daemon thread is a thread that won’t cease the Java Digital Machine (JVM) from exiting when this system is ended, however the thread continues to be working.
Instance:
public class JavaIsDaemonExp extends Thread
{
public void run()
{
//checking for daemon thread
if(Thread.currentThread().isDaemon())
{
System.out.println("daemon thread work");
}
else
{
System.out.println("person thread work");
}
}
public static void foremost(String[] args)
{
JavaIsDaemonExp thread1=new JavaIsDaemonExp();
JavaIsDaemonExp thread2=new JavaIsDaemonExp();
JavaIsDaemonExp thread3=new JavaIsDaemonExp();
thread1.setDaemon(true);
thread1.begin();
thread2.begin();
thread3.begin();
}
}
Output:
daemon thread work
person thread work
person thread work
18. public closing void setDaemon(boolean on)
This technique of a thread is used to establish or mark the thread both daemon or a person thread. The JVM routinely terminates this thread when all of the person threads die.
This thread technique should run earlier than the beginning of the execution of the thread.
Instance:
public class JavaSetDaemonExp1 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("daemon thread work");
}
else
{
System.out.println("person thread work");
}
}
public static void foremost(String[] args)
{
JavaSetDaemonExp1 thread1=new JavaSetDaemonExp1();
JavaSetDaemonExp1 thread2=new JavaSetDaemonExp1();
JavaSetDaemonExp1 thread3=new JavaSetDaemonExp1();
thread1.setDaemon(true);
thread1.begin();
thread2.setDaemon(true);
thread2.begin();
thread3.begin();
}
}
Output:
daemon thread work
daemon thread work
person thread work
19. public void interrupt()
This technique of a thread is used to interrupt the at the moment executing thread. This technique can solely be known as when the thread is in sleeping or ready state.
But when the thread is just not within the sleeping or ready state, then the interrupt() technique is not going to interrupt the thread however will set the interrupt flag to true.
Instance:
public class JavaInterruptExp1 extends Thread
{
public void run()
{
strive
{
Thread.sleep(1000);
System.out.println("javatpoint");
}catch(InterruptedException e){
throw new RuntimeException("Thread interrupted..."+e);
}
}
public static void foremost(String args[])
{
JavaInterruptExp1 thread1=new JavaInterruptExp1();
thread1.begin();
strive
{
thread1.interrupt();
}catch(Exception e){System.out.println("Exception dealt with "+e);}
}
}
Output:
Exception in thread “Thread-0” java.lang.RuntimeException: Thread interrupted…java.lang.InterruptedException: sleep interrupted at JavaInterruptExp1.run(JavaInterruptExp1.java:10)
20. public boolean isInterrupted()
This thread technique is used to check whether or not the thread is interrupted or not. It should return the worth of the interior flag as true or false, i.e. if the thread is interrupted, it can return true else, it can return false.
Instance:
public class JavaIsInterruptedExp extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println("doing activity....: "+i);
}
}
public static void foremost(String args[])throws InterruptedException
{
JavaIsInterruptedExp thread1=new JavaIsInterruptedExp();
JavaIsInterruptedExp thread2=new JavaIsInterruptedExp();
thread1.begin();
thread2.begin();
System.out.println("is thread interrupted..: "+thread1.isInterrupted());
System.out.println("is thread interrupted..: "+thread2.isInterrupted());
thread1.interrupt();
System.out.println("is thread interrupted..: " +thread1.isInterrupted());
System.out.println("is thread interrupted..: "+thread2.isInterrupted());
}
}
Output:
is thread interrupted..: false
is thread interrupted..: false
is thread interrupted..: true
is thread interrupted..: false
doing activity….: 1
doing activity….: 2
doing activity….: 3
doing activity….: 1
doing activity….: 2
doing activity….: 3
21. public static boolean interrupted()
This thread technique is used to test if the present thread is interrupted or not. If this threading technique is to be known as twice in succession, then the second name will return as false.
If the interrupt standing of the thread is true, then this thread technique will set it to false.
Instance:
public class JavaInterruptedExp extends Thread
{
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println("doing activity....: "+i);
}
}
public static void foremost(String args[])throws InterruptedException
{
JavaInterruptedExp thread1=new JavaInterruptedExp();
JavaInterruptedExp thread2=new JavaInterruptedExp();
thread1.begin();
thread2.begin();
System.out.println("is thread thread1 interrupted..:"+thread1.interrupted());
thread1.interrupt();
System.out.println("is thread thread1 interrupted..:"+thread1.interrupted());
System.out.println("is thread thread2 interrupted..:"+thread2.interrupted());
}
}
Output:
is thread thread1 interrupted..: false
is thread thread1 interrupted..: false
is thread thread2 interrupted..: false
doing activity….: 1
doing activity….: 2
doing activity….: 3
doing activity….: 1
doing activity….: 2
doing activity….: 3
22. public static int activeCount()
This technique of the thread is used to return the no. of energetic threads within the at the moment executing thread’s thread group.
The quantity returned by this threading technique is barely an estimate quantity because the variety of threads dynamically adjustments whereas this technique traverses inner knowledge buildings.
Instance:
public class JavaActiveCountExp extends Thread
{
JavaActiveCountExp(String threadname, ThreadGroup tg)
{
tremendous(tg, threadname);
begin();
}
public void run()
{
System.out.println("working thread identify is:"
+Thread.currentThread().getName());
}
public static void foremost(String arg[])
{
ThreadGroup g1 = new ThreadGroup("mother or father thread group");
JavaActiveCountExp thread1 = new JavaActiveCountExp("Thread-1", g1);
JavaActiveCountExp thread2 = new JavaActiveCountExp("Thread-2", g1);
System.out.println("variety of energetic thread: "+ g1.activeCount());
}
}
Output:
variety of energetic thread: 2
working thread identify is: Thread-1
working thread identify is: Thread-2
23. public closing void checkAccess()
This thread technique identifies if the present thread has permission to switch the thread.
Instance:
public class JavaCheckAccessExp extends Thread
{
public void run()
{
System.out.println(Thread.currentThread().getName()+" completed executing");
}
public static void foremost(String arg[]) throws InterruptedException, SecurityException
{
JavaCheckAccessExp thread1 = new JavaCheckAccessExp();
JavaCheckAccessExp thread2 = new JavaCheckAccessExp();
thread1.begin();
thread2.begin();
thread1.checkAccess();
System.out.println(t1.getName() + " has entry");
thread2.checkAccess();
System.out.println(t2.getName() + " has entry");
}
}
Output:
Thread-0 has entry
Thread-1 has entry
Thread-0 completed executing
Thread-1 completed executing
24. public static boolean holdsLock(Object obj)
This thread technique checks if the at the moment executing thread holds the monitor lock on the desired object. If it does, then this threading technique will return true.
Instance:
public class JavaHoldLockExp implements Runnable
{
public void run()
{
System.out.println("At present executing thread is: " + Thread.currentThread().getName());
System.out.println("Does thread holds lock? " + Thread.holdsLock(this));
synchronized (this)
{
System.out.println("Does thread holds lock? " + Thread.holdsLock(this));
}
}
public static void foremost(String[] args)
{
JavaHoldLockExp g1 = new JavaHoldLockExp();
Thread thread1 = new Thread(g1);
thread1.begin();
}
}
Output:
At present executing thread is: Thread-0
Does thread holds lock? false
Does thread holds lock? true
There are numerous thread strategies which can be used for various duties and functions. These thread strategies are as follows:
- public static void dumpStack()
- public StackTraceElement[] getStackTrace()
- public static int enumerate(Thread[] tarray)
- public Thread.State getState()
- public closing ThreadGroup getThreadGroup()
- public String toString()
- public closing void notify()
- public closing void notifyAll()
- public void setContextClassLoader(ClassLoader cl)
- public ClassLoader getContextClassLoader()
- public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()
- public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)
Thread Creation
Whereas multithreading in Java, you’ll be able to create a thread utilizing two methods:
- By extending Thread class
- By implementing the Runnable interface
What’s Thread Class?
Thread class gives the strategies and constructors to create and carry out operations on a thread. Thread class extends Object class and implements the Runnable interface.
Numerous constructors are utilized in a Thread class, however the generally used constructors are:
- Thread()
- Thread(String identify)
- Thread(Runnable r)
- Thread(Runnable r,String identify)
Additionally, as mentioned earlier, there are numerous thread strategies which can be used for various functions and duties.
So, these constructors and strategies are offered by the Thread class to carry out numerous operations on a thread.
What’s a Runnable Interface?
Runnable Interface is carried out whose cases are supposed to be executed by a thread. It has just one technique run().
public void run() – That is used to carry out an motion for a thread.
Beginning a Thread
Whereas multithreading in Java, to start out a newly created thread, the beginning() technique is used.
- A brand new thread begins(with a brand new callstack).
- The thread strikes from the New state to the Runnable state.
- When the thread will get an opportunity to execute, its goal run() technique will run.
Java Thread Instance by extending Thread Class
class Multi extends Thread{
public void run(){
System.out.println("thread is working...");
}
public static void foremost(String args[]){
Multi thread1=new Multi();
thread1.begin();
}
}
Output:
thread is working…
Java Thread Instance by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is working...");
}
public static void foremost(String args[]){
Multi3 m1=new Multi3();
Thread thread1 =new Thread(m1);
thread1.begin();
}
}
Output:
thread is working…
So, this was the fundamental understanding of Multithreading in Java. This brings us to an finish of this weblog. Hope this helped you perceive Multithreading in Java higher and achieve extra insights into it.
Take a look at our weblog on Inheritance in Java to know inheritance ideas higher. To study extra about programming and different associated ideas, try the programs on Nice Studying Academy.
Additionally, do try our prime knowledge science course to up-skill within the area of Knowledge Science and energy forward.
Have a Nice Studying!