You are on page 1of 31

MULTI THREADING IN JAVA

WHAT IS MULTITHREADING?

 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

 It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
 You can perform many operations together, so it saves time.
 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)
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.
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.


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.
 As shown in the 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 CLASS METHODS
S.N. Modifier and Type Method Description
1) void start() It is used to start the execution of the thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
JAVA THREAD CLASS METHODS
S.N. Modifier and Type Method Description
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread object to pause and
allow other threads to execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and all of its subgroups.
17) boolean isDaemon() It tests if the thread is a daemon thread.
18) void setDaemon() It marks the thread as daemon or user thread.
19) void interrupt() It interrupts the thread.
20) boolean isinterrupted() It tests whether the thread has been interrupted.
JAVA THREAD CLASS METHODS
S.N. Modifier and Type Method Description
21) static boolean interrupted() It tests whether the current thread has been interrupted.
22) static int activeCount() It returns the number of active threads in the current thread's
thread group.
23) void checkAccess() It determines if the currently running thread has permission to
modify the thread.
24) static boolean holdLock() It returns true if and only if the current thread holds the monitor
lock on the specified object.
25) static void dumpStack() 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 int enumerate() It is used to copy every active thread's thread group and its
subgroup into the specified array.
28) Thread.State getState() It is used to return the state of the thread.
29) ThreadGroup getThreadGroup() It is used to return the thread group to which this thread
belongs
JAVA THREAD CLASS METHODS
S.N. Modifier and Type Method Description
30) String toString() It is used to return a string representation of this thread,
including the thread's name, priority, and thread group.
31) void notify() It is used to give the notification for only one thread which is
waiting for a particular object.
32) void notifyAll() It is used to give the notification to all waiting threads of a
particular object.
33) void setContextClassLo It sets the context ClassLoader for the Thread.
ader
()
34) ClassLoader getContextClassL It returns the context ClassLoader for the thread.
oader
()
35) static getDefaultUncaug It returns the default handler invoked when a thread abruptly
Thread.UncaughtE htExceptionHandl terminates due to an uncaught exception.
xceptionHandler er()

36) static void setDefaultUncaug It sets the default handler invoked when a thread abruptly
htExceptionHandl terminates due to an uncaught exception.
er()
CREATING A THREAD

 There are two ways to create a thread.


 It can be created by extending the Thread class and overriding its run() method:

class FirstThread extends Thread


{
public void run()
{
System.out.println("Run method executed by
child Thread");
} }
CREATING A THREAD

 Another way to create a thread is to implement the Runnable interface:

Implement Syntax
class SecondThread implements Runnable {
public void run()
{
System.out.println("Run method executed by
child Thread");
}
}
RUNNING THREADS
 If the class extends the Thread class, the thread can be run by creating an instance of the class and call its
start() method:
Extend Example
class FirstThread extends Thread
{
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
FirstThread t = new FirstThread();
t.start();
System.out.println("Main method executed by main thread");
}
}
RUNNING THREADS
 If the class implements the Runnable interface, the thread can be run by passing an instance of the class to
a Thread object's constructor and then calling the thread's start() method:
Implement Example
public class MyClass implements Runnable {
public static void main(String[] args) {
MyClass obj = new MyClass();
Thread thread = new Thread(obj);
thread.start();
System.out.println("This code is outside of the thread");
}
public void run() {
System.out.println("This code is running in a thread");
}
}
DIFFERENCES BETWEEN "EXTENDING" AND
"IMPLEMENTING" THREADS

The major difference is that when a class extends the Thread


class, you cannot extend any other class, but by implementing the
Runnable interface, it is possible to extend from another class as
well, like: class MyClass extends OtherClass implements
Runnable.
class SecondThread extends OtherClass implements Runnable {
public void run()
{
System.out.println("Run method executed by child Thread");
}
public static void main(String[] args)
{
SecondThread t = new SecondThread();
t.m1();
Thread t1 = new Thread(t);
t1.start();
System.out.println("Main method executed by main thread");
}
}
BASIS FOR COMPARISON THREAD RUNNABLE
Basic Each thread creates a unique Multiple threads share the same
object and gets associated with objects.
it.
Memory As each thread create a unique As multiple threads share the
object, more memory required. same object less memory is
used.

Extending In Java, multiple inheritance not If a class define thread


allowed hence, after a class implementing the Runnable
extends Thread class, it can not interface it has a chance of
extend any other class. extending one class.
Use A user must extend thread class If you only want to specialize
only if it wants to override the run method then implementing
other methods in Thread class. Runnable is a better option.

Coupling Extending Thread class Implementing Runnable


introduces tight coupling as the interface introduces loose
class contains code of Thread coupling as the code of Thread
class and also the job assigned is separate form the job of
to the thread Threads.
CONCURRENCY PROBLEMS

 Because threads run at the same time as other public class ConcurrentProblem extends Thread{
public static int amount =0;
parts of the program, there is no way to know public void run(){
in which order the code will run. When the amount++;
threads and main program are reading and }
writing the same variables, the values are
unpredictable. The problems that result from public static void main(String arg[])
{
this are called concurrency problems. ConcurrentProblem CP=new ConcurrentProblem();
Example CP.start();
System.out.println(amount);
 A code example where the value of the amount++;
variable amount is unpredictable: System.out.println(amount);
}
}
public class ConcurrentProblem extends Thread{
CONCURRENCY PROBLEMS public static int amount =0;
public void run(){
amount++;
}
 To avoid concurrency problems, it is best to public static void main(String arg[])
{
share as few attributes between threads as ConcurrentProblem CP=new ConcurrentProblem();
possible. If attributes need to be shared, one CP.start();
possible solution is to use the isAlive()
//wait for thread to finish
method of the thread to check whether the
thread has finished running before using any while(CP.isAlive()) {
attributes that the thread can change. System.out.println("Waiting...");
}
Example
System.out.println("Main" + amount);
 Use isAlive() to prevent concurrency amount++;
problems: System.out.println("Main"+amount);
}
}
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 OF SLEEP METHOD IN JAVA
class TestSleepMethod1 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[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}
CAN WE START A THREAD TWICE

public class TestThreadTwice1 extends Thread{

 No. After starting a thread, it can never public void run(){


be started again. If you does so, System.out.println("running...");
an IllegalThreadStateException is }
thrown. In such case, thread will run public static void main(String args[]){
once but for second time, it will throw TestThreadTwice1 t1=new
exception. TestThreadTwice1();
 Let's understand it by the example given: t1.start();
t1.start();
}
}
WHAT IF WE CALL RUN() METHOD DIRECTLY INSTEAD START()
METHOD?

class TestCallRun1 extends Thread{


public void run(){
 Each thread starts in a separate call
System.out.println("running...");
stack. }
 Invoking the run() method from public static void main(String args[]){
main thread, the run() method goes TestCallRun1 t1=new TestCallRun1();
onto the current call stack rather t1.run();//fine, but does not start a separate call
than at the beginning of a new call stack
stack. } Output: running...
}
class TestCallRun2 extends Thread{   Output:1
 public void run(){   2
  for(int i=1;i<5;i++){   3
    try{Thread.sleep(500);}catch(InterruptedExce 4
ption e){System.out.println(e);}   5
    System.out.println(i);   1
  }   2
 }   3
 public static void main(String args[]){   4
  TestCallRun2 t1=new TestCallRun2();   5
  TestCallRun2 t2=new TestCallRun2();  
   
  t1.run();  
Note:
  t2.run();  
As you can see in the above program that there is no context-
 }  
switching because here t1 and t2 will be treated as normal

object not thread object.
public class TestJoinMethod1 extends Thread {

THE JOIN() METHOD 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);
}}
 The join() method waits for a thread to die. In other
public static void main(String arg[])
words, it causes the currently running threads to stop {
executing until the thread it joins with completes its TestJoinMethod1 t1=new TestJoinMethod1();
task. TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
Example of join() method
t1.start();
try{
public void join()throws InterruptedException t1.join();
public void join(long milliseconds)throws InterruptedException}catch(Exception e){System.out.println(e);}
t2.start();
in this example, when t1 completes its task then t3.start();
}
t2 and t3 starts executing.
}
Example of join(long miliseconds) method

public class TestJoinMethod2 extends Thread {


run:
public void run(){
for(int i=1;i<=5;i++)
1
{ 2
try{ 3
Thread.sleep(500); 1
}catch(Exception e){System.out.println(e);} 1
System.out.println(i); 4
}} In this example, when t1 is
2
public static void main(String arg[]) completes its task for 1500
2
{ miliseconds (ie; 3 times) then t2
TestJoinMethod2 t1=new TestJoinMethod2();
5
and t3 starts executing.
TestJoinMethod2 t2=new TestJoinMethod2(); 3
TestJoinMethod2 t3=new TestJoinMethod2(); 3
4
t1.start(); 4
try{ 5
t1.join(1500); 5
}catch(Exception e){System.out.println(e);}
BUILD SUCCESSFUL (total time: 4
t2.start();
seconds)
t3.start();
}
}
getName(),setName(String) and getId() method:
public class TestJoinMethod3 extends Thread {

public void run(){


System.out.println("running...");
} run:
public static void main(String arg[]) Name of t1:Thread-0
{ Name of t2:Thread-1
TestJoinMethod3 t1=new TestJoinMethod3(); id of t1:10
TestJoinMethod3 t2=new TestJoinMethod3(); After changing name of t1:Java Program
System.out.println("Name of t1:" + t1.getName()); running...
System.out.println("Name of t2:" + t2.getName()); running...
System.out.println("id of t1:"+t1.getId()); BUILD SUCCESSFUL (total time: 0 seconds)

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

t1.setName("Java Program");
System.out.println("After changing name of
t1:"+t1.getName());
}
}  
The currentThread() method:
The currentThread() method returns a reference to the currently executing thread object.

class TestJoinMethod4 extends Thread{


public void run()
{

System.out.println(Thread.currentThread().getName());
}
public static void main(String args[])
{ run:
TestJoinMethod4 t1=new TestJoinMethod4(); Thread-0
TestJoinMethod4 t2=new TestJoinMethod4(); Thread-1
BUILD SUCCESSFUL (total time: 0
t1.start(); seconds)
t2.start();
}
}
To be Continued…

You might also like