CH2-Multithreading
CH2-Multithreading
Program:
class Current
{
public static void main(String [] args)
{
System.out.println(" Check the current Thread:");
Thread t= Thread.currentThread();
System.out.println("Current Thread : "+t);
System.out.println(" Thread Name :" + t.getName());
}
}
Def.: A program can be divided into a number of small processes. Each small
process can be addressed as a single thread (a lightweight process).
OR
A Thread is a very light-weighted process, or we can say the smallest part of the
process that allows a program to operate more efficiently by running multiple tasks
simultaneously.
In order to perform complicated tasks in the background, Thread concept was introduced in Java.
All the tasks are executed without affecting the main program.
In a program or process, all the threads have their own separate path for execution, so each thread of a
process is independent.
Another benefit of using thread is that if a thread gets an exception or an error at the time of its
execution, it doesn't affect the execution of the other threads.
All the threads share a common memory and have their own stack, local variables and program
counter.
When multiple threads are executed in parallel at the same time, this process is known
as Multithreading.
Multithreaded programs contain two or more threads that can run concurrently and each thread
defines a separate path of execution. This means that a single program can perform two or more tasks
simultaneously.
For example, one thread is writing content on a file at the same time another thread is performing
spelling check.
Why Multithreading?
The thread has many advantages over the process to perform multitasking. The process is heavy, takes
more memory, and occupiesthe CPU for a longer time which may lead to performance issues with the
system. To overcome this issue process is broken into small units of independent sub-processes. These
sub-processes are called threads that can perform independent tasks efficiently. So nowadays computer
systems prefer to use thread over the process and use multithreading to perform multitasking.
Main Thread:
When we run any java program, the program begins to execute its code starting from the main
method. Therefore, the JVM creates a thread to start executing the code present in main method. This
thread is called as main thread.
Although the main thread is automatically created, you can control it by obtaining a reference to it by
calling currentThread() method.
Two important things to know about main thread are:
o It is the thread from which other threads will be produced.
o It must be always the last thread to finish execution
PROGRAM1:
class MultithreadingDemo extends Thread
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemoobj=new MultithreadingDemo();
obj.start();
}
}
PROGRAM:
class MyThread extends Thread {
public void run() {
for(inti=1;i<=10;i++)
System.out.println("Child Thread");
}
}
PROGRAM 2:
class MultithreadingDemo1 implements Runnable
{
public void run()
{
System.out.println("My thread is in running state.");
}
public static void main(String args[])
{
MultithreadingDemoobj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Important methods of Thread class
Method Description
setName() To give thread a name
getName() Return thread's name
getPriority() Return thread's priority
isAlive() Checks if thread is still running or not
join() Wait for a thread to end
run() Entry point for a thread
sleep() Suspend thread for a specified time
start() Start a thread by calling run() method
activeCount() Returns an estimate of the number of active threads in the current
thread's thread group and its subgroups.
checkAccess() Determines if the currently running thread has permission to
modify this thread.
currentThread() Returns a reference to the currently executing thread object.
getId() Returns the identifier of this Thread.
getState() Returns the state of this thread.
interrupt() Interrupts this thread.
isAlive() Tests if this thread is alive.
isDaemon() Tests if this thread is a daemon thread.
isInterrupted() Tests whether this thread has been interrupted.
setPriority(intnewPriority) Changes the priority of this thread.
yield() A hint to the scheduler that the current thread is willing to yield
its current use of a processor.
EXAMPLE:
class Current
{
public static void main(String [] args)
{
System.out.println(" Check the current Thread:");
Thread t= Thread.currentThread();
System.out.println("Current Thread : "+t);
System.out.println(" Thread Name :" + t.getName());
System.out.println(" Thread ID :" + t.getId());
System.out.println(" Thread State :" + t.getState());
System.out.println(" Thread Active Count:" + Thread.activeCount());
System.out.println(" Thread Priority:" + t.getPriority());
System.out.println(" Thread isAlive:" + t.isAlive());
System.out.println(" Thread isDaemon:" + t.isDaemon());
System.out.println(" Thread isInturrupted:" + t.isInterrupted());
}
}
Thread Constructors
Thread T1=new Thread();
Thread T1=new Thread(Runnable obj);
Thread T1=new Thread(String name);
Thread T1=new Thread(Runnable obj, String name);
Thread T1=new Thread(ThreadGroup grp, String name);
Thread T1=new Thread(ThreadGroup grp, Runnable obj);
Thread T1=new Thread(ThreadGroup grp, Runnable obj, String name);
Thread T1=new Thread(ThreadGroup grp, Runnable obj, String name, long stacksize) ;
Every thread in JAVA has some name, default name generated by JVM or customized
name provided by programmer.
WE can get and set thread name by using methods setName() and getName()
EXAMPLE:
class MyThread extends Thread {
public void run() {
}
}
Thread.currentThread Method:
We can get current running executing thread by Thread.currentThread() method.
EXAMPLE:
class MyThread extends Thread {
public void run() {
System.out.println("Run executed by:"+Thread.currentThread().getName());
}
}
}
}
Thread Priorities:
Each thread have a priority. Priorities are represented by a number between 1 and 10.
Three constants defined in Thread class:
public static int MIN_PRIORITY
public static int NORM_PRIORITY
public static int MAX_PRIORITY
Thread class defines following methods to get and set priorities of thread
public final intgetPriority();
public final void setPriority(int);
For setPriority() method allowed range of values is 1 to 10 otherwise it will raise
IllegalArgumentException will be raised.
Default priority for every child thread is inherited from parent thread.
The Main thread has default priority as 5 i.e. Thread.NORM_PRIORITY
When T1 threads gets chance to execute it pauses and gives chance to execute Main thread
join() Method:
o The join() method of a Thread instance is used to join the start of a thread’s execution to the
end of another thread’s execution such that a thread does not start running until another
thread ends.
o If join() is called on a Thread instance, the currently running thread will block until the
Thread instance has finished executing.
o Consider T1 and T2 threads,
if T1 wants to wait until T2 completes then T1 has to call T2.join().
when T1 executes T2.join(), T1 enters into waiting state until T2 completes its
execution.
Once T2 completes then T1 can continue its execution.
o EX: considers T1: ResultPrinting T2:NameCorrection are the threads, here also T1 needs to
call T2.join as T1 can continue its execution after until T2 completes execution.
o Syntax: public final void join()
o Every join method throws InterruptedException
sleep() Method
o This method causes the currently executing thread to sleep for the specified number of
milliseconds.
o The method sleep() is being used to halt the working of a thread for a given amount of time.
o The time up to which the thread remains in the sleeping state is known as the sleeping time of
the thread.
o After the sleeping time is over, the thread starts its execution from where it has left.
o
public static void sleep(long mls) throws InterruptedException
public static void sleep(long mls, int n) throws InterruptedException
o Whenever another thread does interruption while the current thread is already in the sleep
mode, then the InterruptedException is thrown.
o Thread.sleep() method can be used with any thread. It means any other thread or the main
thread can invoke the sleep() method.
o EXAMPLE:
class MyThread extends Thread {
public void run()
{
try
{
for(inti=1;i<=10;i++)
{
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{System.out.println("InterruptedException");
}
}
}
SETA 1,2
The thread can interrupt a sleeping thread or waiting thread by using interrupt() method
Synchronization:
In Java multiple threads runs parallel to complete their execution.
We need to synchronize the shared resources to ensure that at a time only one thread is able to access
the shared resource.
If an Object is shared by multiple threads then there is need of synchronization in order to avoid the
Object’s state to be getting corrupted.
Synchronization is needed when Object is mutable. If shared Object is immutable or all the
threads which share the same Object are only reading the Object’s state not modifying then you don’t
need to synchronize it.
Java programming language provide two synchronization idioms:
o Methods synchronization
o Statement(s) synchronization (Block synchronization)
Method Synchronization:
Synchronized methods prevents the thread interference and memory consistency errors.
If an Object is visible to more than one threads, all reads or writes to that Object’s fields are done
through the synchronized method.
It is not possible for two invocations for synchronized methods to interleave.
If one thread is executing the synchronized method, all others thread that invoke synchronized
method on the same Object will have to wait until first thread is done with the Object.
EXAMPLE:
class TestMyThreadTable
{
public static void main(String [] args)
{
MyThreadTable T1 = new MyThreadTable (5);
MyThreadTable T2 = new MyThreadTable (8);
T1.start();
T2.start();
}
}
Block Synchronization:
If we only need to execute some subsequent lines of code not all lines (instructions) of code within a
method, then we should synchronize only block of the code within which required instructions are
exists.
For example, lets suppose there is a method that contains 100 lines of code but there are only 10 lines
(one after one) of code which contain critical section of code i.e. these lines can modify (change) the
Object’s state. So we only need to synchronize these 10 lines of code method to avoid any
modification in state of the Object and to ensure that other threads can execute rest of the lines within
the same method without any interruption.
EXAMPLE:
void Display()
{
for(inti=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+i+"Before Sync. Block");
synchronized(this)
{
for(inti=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+i+"In Sync. Block");
}
for(inti=1;i<=5;i++)
System.out.println(Thread.currentThread().getName()+":"+i+"After Sync. Block");
}
}
class TestSyncBlock
{
public static void main(String [] args)
{
SyncBlock T1 = new SyncBlock ();
SyncBlock T2 = new SyncBlock ();
T1.start();
T2.start();
}
}
Inter Thread Communication in Java
Inter-thread communication in Java is a technique through which multiple threads communicate with
each other
There are several situations where communication between threads is important.
For example, suppose that there are two threads A and B. Thread B uses data produced by Thread A
and performs its task.
If Thread B waits for Thread A to produce data, it will waste many CPU cycles. But if threads A and
B communicate with each other when they have completed their tasks, they do not have to wait and
check each other’s status every time.
Inter thread communication in Java can be achieved by using three methods
1. wait() 2. notify() 3. notifyAll()
Note-These methods can be called only from within a synchronized method or synchronized
block of code
To call wait(), notify(), notifyAll() in any object thread should be owner of that object (i.e thread
should have lock on the object) so wait, notify and notifyAll from synchronized area otherwise we
will get runtime exception IllegalMonitorException
wait():
o If thread calls wait() method on any object it immediately releases lock of that particular
object and enters into waiting state.
o calling wait() forces the current thread to wait until some other thread
invokes notify() or notifyAll() on the same object.
notify(): if thread calls notify method on any object it releases lock of that object but may not
immediately. except wait, notify and notifyAll there is no other method where thread releases lock.
EXAMPLE:
/*Write a java program for to solve producer consumer problem in which a producer produce a value and
consumer consume the value before producer generate the next value.*/
class Buffer
{
int value;
boolean produced=false;
public synchronized void produce(int x)
{
if(produced)
{ try
{
wait();
}
catch(Exception e)
{ System.out.println(e); }
}
value=x;
System.out.println(value+"is produced");
produced=true;
notify();
}
class ProducerConsumer
{
public static void main(String arr[])
{
Buffer b=new Buffer();
Producer p=new Producer(b);
Consumer c=new Consumer(b);
p.start();
c.start();
}
}
---------------xxxxxxxxxxxxx--------------