UNIT NO-5
Multithreading in Java
What is
MULTI TASKING MULTI PROCESSING MULTI THREADING
Performing multiple task at When one system getting Executing multiple
single time. connected with multiple threads(sub process,sub
processor in order to complete tasks) at single unit time
VLC Browse the task
Word
r VLC
VLC Browse
Word
r
OS Audi Vide Time
o o r
OS
CPU
OS
USES: Increase the
performance of the CPU. CPU CPU CPU
CPU
TYPES: It is best suitable for OS level USE-
1)Process based or system level. Software
2)Thread based Animation
Gaming
Questions
Interpret the terms multitasking and
multiprocessing and multithreading in Java with
example. [6]
Multithreading is best suitable at programming level.
Java provide predefined API for multithreading
Like Thread,Runnable,ThreadGroup,
Concurrency,ThreadPool
Implement
1)Multi-threading by extending thread class.
2)By implementing runnable interface.
1)Thread class 2)Runnable Interface
1)Thread class 2)Runnable Interface
package java.lang package java.lang
public class Thread
{ Public interface Runnable
//multiple constructor {
//multiple methods //method
run() run()
start() }
}
1)Thread class example 2)Runnable interface example
package java.lang package java.lang
class Test extends Thread //extends thread class Test implements Runnable //implement runnable
class interface
{ {
public void run() //override run method
public void run() //override run {
method System.out.println(“Thread started”); //task of
{ thread
//Task of thread System.out.println(“Thread }
started”); public static void main(String args[])
} {
public static void main(String args[]) Test t=new Test(); //create object of test class
{ Thread th=new Thread(t); //create object of test
Test t=new Test(); //create object of test class
class
t.start(); //invoke the thread th.start(); //invoke the thread
execute
run() method. }
t.start() //gives error we do not.
invoke thread again
2)Thread life Cycle
Thread Is well known for independent execution. during the execution of thread it
moves from different states.
t.suspend()
t.join()
t.sleep()
blocked t.wait()
t.start( t.start(
) t.run()
)
Born Ready Running Dead
t.stop(
New State(Born) )
Runnable state(Ready)
Running State(Execution)
Waiting State(Blocked)
Dead state(exit)
New Thread: When a new thread is created, it is in the new state. The thread has not yet started to run
when the thread is in this state
Runnable State: A thread that is ready to run is moved to a runnable state. In this state, a thread might
actually be running or it might be ready to run at any instant of time. It is the responsibility of the thread
scheduler to give the thread, time to run. A multi-threaded program allocates a fixed amount of time to
each individual thread. Each and every thread get a small amount of time to run.
Blocked: The thread will be in blocked state when it is trying to acquire a lock but currently the lock is
acquired by the other thread.
Waiting state: The thread will be in waiting state when it calls wait() method or join() method. It will
move to the runnable state when other thread will notify or that thread will be terminated.
Timed Waiting: A thread lies in a timed waiting state when it calls a method with a time-out parameter. A
thread lies in this state until the timeout is completed or until a notification is received. For example, when
a thread calls sleep or a conditional wait, it is moved to a timed waiting state.
Terminated State: A thread terminates because of either of the following reasons:
Because it exits normally. This happens when the code of the thread has been entirely executed by the
program.
Because there occurred some unusual erroneous event, like a segmentation fault or an unhandled
exception.
Exception handling
What is Exception?
Exception:A exception is a unwanted or unexpected
event .which occurs during the execution of a program.i.e at
run time,that disturbs the normal flow of program.
Ex-File not found,ill exception,Power cut exception.
What is Exception handling?
In exception handling.we should have an alternate
source.through which we can handle the exception.
Example Program
class A class A
{ {
Public static void main(String Public static void main(String
args[]) args[])
{ {
System.out.println(“1”); int a=10,b=0,c;
System.out.println(“2”); c=a/b;
System.out.println(“10/0”); System.out.println(c);
System.out.println(“3”);
System.out.println(“4”); }
} }
Exception: Exception:
ArithmaticException ArithmaticException
Exception Handling Methods
1)Try 2)Catch 3)throw 4)throws 5)finally
Program with Exception Program without Exception
class A class A
{ {
Public static void main(String args[]) Public static void main(String args[])
{ {
int a=10,b=0,c; int a=10,b=0,c;
c=a/b; System.out.println(“Main thread Started”);
System.out.println(c); try()
{
} c=a/b;
} System.out.println(c);
Exception: }
ArithmaticException catch(Exception e)
{
System.out.println(e);
}
System.out.println(“Main thread Ended”);
}
}
o/p- Main thread started
Arithmetic Exception.
Main thread Ended
Join() Method in thread
Def:-If a thread wants to wait for another thread to complete its task.
Then we should use join() Method.
Ex-Licence
T2 T3
T1
Test Officers
Medical
Drive sign
Methods of Join()
1)public final void join() throws IntrruptedException {---}
2)public final synchronized void join(long ms) throws IntrruptedException {---}
3)public final synchronized void join(long ms,int ns) throws IntrruptedException {---}
Join() method program
public class Test extends Thread Public static void main(String
{ args[])throws IntrruptedException
public void run() {
{ Test t=new Test();
Try() t.start();
{ t.join();
For(int i=1;i<5;i++) Try()
{ {
System out println(“Child For(int i=1;i<5;i++)
thread”+i); { Output
Thread.sleep(1000); System out println(“Main thread”+i);Child thread 1
} Thread.sleep(1000); Child thread 2
} } Child thread 3
catch(Exception e) } Child thread 4
{ catch(Exception e) Child thread 5
System.out.println(e); { Main thread1
} System.out.println(e); Main thread2
} } Main thread 3
} } Main thread 4
Main thread 5
What is isAlive() Method
Defination: isAlive() is a predefined method of Thread class.Through which
we can verify whether thread is alive or not .
Note:-1) If Thread is Alive then it return true otherwise it return false.
2)If we use isAlive() method before start() method.Then it will print false but
after the start() method it will print true.
Program for isAlive() method
class A extends Thread class B
{ { False
public void run() public static void main(String True
{ args[]) isAlive method program…
System.out.println(“isAlive {
method program…”); A t1=new A();
} A t2=new A();
}
System.out.println(t1.isAlive(
));
t1.start();
System.out.println(t1.isAlive(
));
System.out.println(t2.isAlive(
));
t2.start();
System.out.println(t2.isAlive(
));
}
}
What is Thread priority(I.M.P)
In java it is possible to assign the priority of threads .to set the priority
java thread class is provided. It consist of two predefine methods
1)setpriority()
2)getpriority()
The thread class also provided three pre-defined final static variable &
its value lie in between 1 to 10.
1)Thread.MIN_PRIORITY=1
2)Thread.NORM_PRIORITY=5
3)Thread.MAX_PRIORITY=10
Program for
getName(),setName(),getPriority(),setPriority()
class A extends Thread t1.setPriority(3);
{ t2.setPriority(7);
public void run() t3.setPriority(5);
{
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName( t3.start();
)); }
}
System.out.println(Thread.currentThread().getPriorit
y()); Output:
} t2 thread
} 7
t3 thread
class B
5
{ t1 thread
public static void main(String args[]) 3
{
A t1=new A();
A t2=new A();
A t3=new A();
t1.setName(“ t1 Thread”);
Questions
Q.Explain the uses of isAlive() and Join() methods in Java thread with
example. [6]
Q) Elaborate the terms getPriority() and setPriority() methods with example.
[6]
What is Thread Synchronization
Synchronization is a technique through which we can control
multiple threads .or among the no of threads only one thread will
enter inside synchronized area.
Note-Main purpose of synchronization is to overcome the problem
of multithreading when multiple threads are trying to access same
resources at same time on that situation it may provides some wrong
result.
Synchronization is broadly classified into two types.
1)Method Level Synchronization
2)Block Level Synchronization
1)Method Level Synchronization
Syntax Example
Public void run() Bank joint account
{
//resource
}
t1.start();
t2.start();
t3.start();
public synchronized void run()
{
//resource
}
t1.start();
t2.start();
t3.start();
2)Block level synchronization
Syntax Example
Public void hotel() Sweet
{
Synchronized(this)
{
//resource
}
}
t1.start();
t2.start();
t3.start();
Interthread Communication wait(), notify(),
notifyall()