0% found this document useful (0 votes)
1 views12 pages

Multi Threading Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views12 pages

Multi Threading Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

Multithread:

1)Introduction
2)The ways two define a Thread.
a)By extending Thread class
b)By implementing Runnable(I)
3)Getting and setting name of the Thread
4)Thread priorities
5)The methods to prevent Thread execution
a)yield()
b)join()
c)sleep()
6)synchronization
7)Inter Thread communication
8)DeadLock
9)Deamon Threads
10)Multithreading enhancement

1. Introduction:

multitasking:
-->Excecuting several tasks simultaneously is the concept of multitasking.
-->Threre are two types of multitaskings.

process based multitasking


thread based multitasking

process based:

-->Excecuting several tasks simultaneously where each task is separate independent


program(process) is called process based multitasking.

example:
while typing java program in the editor we can listen audio songs from the same
system at same time we can download a file from net all these
tasks will be executed simultaneously and independent of each other
hence it is process based multi tasking.

-->process based multi tasking best suitable at os level.

thread based multitasking:

-->Excecuting several tasks simultaneously where each task is a separate


indedependent part of the same program is called thread based multi tasking
and each independent part is called a thread.

-->thread based multi tasking best suitable at programatic level.

Note:wheather it is process based or thread based the main objective of


multitasking is to reduce response time of the system and to improve performance.

-->The main important application areas of multithreading are,

*To develop multimeadia graphics.


*to develop animations
*to develop video games
*to develop web servers and application servers.
-->when compared with old languages developing multithreaded applications in java
is very easy because java provides in built support for multithreading with rich
API[Thread,Runnable,ThreadGroup]

Defining Thread:

-->We can define a thread in the following two ways

------>by extending thread class


------>by implementing Runnable interface.

by extending thread class:

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
s.o.pln("child thread ");
}
}

class ThreadDemo
{
p s v main(String[] args)
{
myThread t=new myThread();
t.start();
for(int i=0;i<10;i++)
{
s.o.pln("main thread ");
}
}
}

Thread Schedular:

-->It is the part of JVM, it is responsible to schedule threds that is if multiple


threads are waiting to get the chance of execution then in which order threads
will be executed is decided by thread schedular.

-->we cannot expect exact algorithm followed by thread schedular it is varied


from JVM to JVM hence we cannot expect threads execution order and exact output.

-->Hence whenever situation comes multithreading there is no


gaurantee for exact output but we can provide sevaral possible outputs.

case-2:diff b/w start() and run():

-->In the case of t.start() new thread will be created which is responsible for
the execution of run() method

--> but in the case t.run() a new thread won't be created and run() will be
executed
just like a normal method call by main thread.
-->hence in the above program if we replace t.start() with t.run()
then the output is 'childthread 10 times followed by mainthread 10 times',
this total output produced by only maintread.

by using Runnable interface:

class MyRunnable implements Runnable


{
public void run()
{
for(int i=0;i<10;i++)
{
s.o.pln("child thread ");
}

class ThreadDemo
{
p s v main(String[] args)
{
myRunnable r=new myRunnable();
Thread t1=new Thread(r);
t1.start();
for(int i=0;i<10;i++)
{
s.o.pln("main thread ");
}
}
}

thread priorities:

-->Every thread in java has some priority it may be default priority generated by
JVM
customized priority provided by programmer.
-->THe vallid range of thread priorities is 1 to 10 where 1 is min priority
and 10 is max priority

-->Thread class defines the following constants to represent some standard


priorities

Thread.MIN_PRIORITY is 1
Thread.NORM_PRIORITY is 1
Thread.MAX_PRIORITY is 10

-->thread schedular will use priorities while allocating processor


-->The thread which is having highest priority will get chance first.
-->I f two thrads having same priority then we cannot expect exact executionn order
it depends on thread schedular.

--> thread class defines the following methods to get and set priority of a thread

-------->public final int getPriority();


--------->public final void setPriority(int p);

ex:
t.setPriority(7);//valid
t.setPriority(17);//invalid

Default Priority:

-->The default priority only for the main thread is 5.


-->But for all remaining threads default priority will be inherited
from parent to chaild i.e., whatever priority parent thread has the same
priority will be there for the child thread.

Example:

class MyThread extends Thread{


}
class Test
{
p s v main(String[] args)
{
s.o.pln(Thread.currentThread().getPriority());
Thread.currentThread().setPriority(15);
Thread.currentThread().setPriority(7);
MyThread t=new MyThread();
S.o.pln(t.getPriority());

}
}

The methods to prevent Thread execution:

-->we can prevent a thread execution by using the following methods

---------->yield();
---------->join();
---------->sleep();

yield():

-->yield() causes to pause current executing thread to give the chance


for waiting threads of same priority.
If there is no waiting thread have low priority then same thread
can continue its execution.

-->If multiple threads are waiting with same priority then which
waiting thread will get the chance wecanot expect it depends on schedular.

-->The thread which is yielded, when it will get the chance once
again it depends on thellohread schedular and we canot expect exactly.

-->public static native void yield();

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
s.o.pln("child Thread");
Thread.yield();
}
}
}

class ThreadYield
{
public static void main(String[] args)
{
MyThread t=new MyThread();
t.start();
}
}

join();

-->If a thread wants to wait until completing some other thread then we should go
for
join() method.
-->For example if a thread t1 wants to wait until completing t2 then t1 has to call
"t2.join()".
-->If t1 executes "t2.join()" then immediately t1 will be entered into waiting
state
until t2 completes.
-->once t2 completes then t1 can continue its execution

-->public final void join() throws InterruptedException;


-->public final void join(long ms) throws InterruptedException;
-->public final void join(long ms, int ns)throws InterruptedException;

Example:

class MyThread extends Thread


{
public void run()
{
for(int i=0;i<10;i++)
{
s.o.pln("child Thread");
try{
Thread.sleep(2000);
}
catch(InterruptedException e){
}
}
}
}

class ThreadJoin
{
public static void main(String[] args) throws InterruptedException
{
MyThread t=new MyThread();
t.start();
t.join();
for(int i=0;i<10;i++){
s.o.pl("main thread");
}
}
}

///waiting child

class MyThread extends Thread


{
static Thread mt;
public void run()
{
try{
mt.join();
}
catch(InterruptedException e){
}
for(int i=0;i<10;i++)
{
s.o.pln("child Thread");

}
}
}

class ThreadJoin
{
public static void main(String[] args) throws InterruptedException
{
MyThread.mt=Thread.currentThread();
MyThread t=new MyThread();
t.start();
for(int i=0;i<10;i++){
s.o.pl("main thread");
Thread.sleep(2000);
}
}
}

sleep();

-->If a thread don't want to perform any operation for a particular amount of time
then we should go for sleep();

-->public static native void sleep(long ms) throws InterruptedException;


-->public static void sleep(long ms, int ns)throws InterruptedException;

class SlideRotator
{
p s v main(String[] args) throws InterruptedException
{
for(int i=0;i<10;i++)
{
s.o.pln(i);
Thread.sleep(5000);
}
}

How athread is interrupted another thread:


--> A thread can interrupt a sleeping thread or waiting thread by using interrupt()
of thread class.

-->public void interrupt();

class MyThread extends Thread


{
public void run()
{
try{
for(int i=0;i<10;i++)
{
s.o.pln("child Thread");
Thread.sleep(2000);
}
}
catch(InterruptedException e){
s.o.pln("interrupted");

}
}

class ThreadJoin
{
public static void main(String[] args) throws InterruptedException
{
MyThread t=new MyThread();
t.start();
t.interrupt();
s.o.pl("main thread");

}
}

Daemon Threads:

-->the thread which is executing at the background is called daemon threads.

----------->gc
----------->attach Listener
----------->Signal dispacher

-->The main objective of daemon thread is to provide support for non deamon
threads(main thread).
-->For example main thread runs with low memory then jvm runs gc to destroy use
less objects.
-->useally daemon thread having low priority but based on our requirement daemon
threads can run with high priority also

-->public boolean isDaemon();


-->public void setDaemon(boolean b);
class MyThread extends Thread{}
class Test
{
p s v main(String[] args)
{
s.o.pln(Thread.currentThread().isDaemon());

Thread.currentThread().setDaemon(true);
MyThread t=new MyThread();
s.o.pln(t.isDaemon());
t.setDaemon(true);
s.o.pln(t.isDaemon());
}
}

Green Thread:

-->Java multithreading concept implemented by using the following two models


------------->Green Thread Mdel
------------->Native os Model

Green Thread Model:

-->The thread which is managed completely by jvm without taking underlying os


support is called Green thread.

-->very few os like sun solaris provide support for green thread model

-->Anyway green thread model is depricated not recommended to use

Native os Model:
-->The thread which is managed by the Jvm with the help underlying os,
is called native os model.

-->all windows based os provide support for native os model

How to stop a thread:

-->public void stop();

How to suspend and resume of a thread:

-->we can suspend a thread by using suspend method of thread class then
immediately the thread will be entered into suspended state.
-->we can resume a suspended thread by using resume() of thread class then
suspended thread can continue its execution.

-->public void suspend();


-->public void resume();

-->Anyway these methods are deprecated not recommended to use

Synchronization:

-->If multiple threads are trying to operate simultaneously on the same java object
then there may be a chance of data inconsistancy problem.
-->to overcome this problem we should go for synchronized keyword
-->if a method or block declared as synchronized then at a time only one thread is
allowed to execute that method or block on the given object so that data
inconsistancy problem will be resolved.

-->the main advantage of synchronized keyword is we can resolve data iconsistancy


problem but the main disadvantage of synchronized keyword is it increases waiting
time of thread and creates performance problem , hence if there is no specific
requirement then it not recommanded to use synchronized keyword.

-->internally synchronization concept is implemented by using lock.


-->every objectin java has a unique lock.whenever we are using synchronized keyword
then only lock concept will come into the picture.
-->If a thread wants to execute synchronized method and given object first it has
to get lock of that object.once thread got the lock then it is allowed to execute
any synchronized method on that object, once method execution completes
automatically thread releases the lock.
-->aquiring and releasing lock internally takes care by jvm and programmer not
responsible for this activity.

Example:

class Display
{
public synchronized void wish(String name)
{

for(int i=0;i<10;i++)
{
s.o.pln("Good Morning:");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{}
}
s.o.pln(name);
}
}

class MyThread extends Thread


{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
}
class SynchronizedDemo{
p.s v main(String[] args)
{
Display d=new Display();
MyThread t1=new MyThread(d,"anil");
MyThread t2=new MyThread(d,"abhi");
t1.start();
t2.start();
}
}
InterThread Communication:

-->two threads can communicate with each other by using wait(), notify() and
notifyall() methods.
-->the thread which is expecting updation is resposible to call wait(), then
immeadiately entered into waiting state
-->the thread which is resposible to perform updation, after performing updation it
is responsible to call notify method then waiting thread will get that notification
and continue its execution with those updated items.

-->public final void wait() throws InterruptedException;


-->public final native void wiat(long ms)throws InterruptedException;
-->public final void wait(long ms, int ns)throws InterruptedException;

-->public final native void notify();


-->public final native void notifyAll();

class ThreadA
{
public static void main(String[] args)
{
ThreadB b=new ThreadB();
b.start();
b.wait();
s.o.pln(b.total);
}
}

class ThreadB extends Thread


{
int total=0;
public void run()
{
for(int i=1;i<100;i++)
{
total=total+i;
}
this.notify();
}
}

//synchronization:

class ThreadA
{
public static void main(String[] args)
{
ThreadB b=new ThreadB();
b.start();

synchronized()
{
b.wait();
s.o.pln(b.total);
}
}
}

class ThreadB extends Thread


{
int total=0;
public void run()
{
synchronized(this)
{
for(int i=1;i<100;i++)
{
total=total+i;
}
this.notify();
}
}
}

DeadLock:

-->two threads are waiting for each other for ever such type of infine waiting is
called DeadLock.

-->synchronized keyword is the only reason for deadlock situation.hence while using
synchronized keyword we have to take special care.
-->There are no resolution techniques for deadlock, but sevaral prevention
techniques are available

example:

class A{
public synchronized void d1(B b)
{
s.o.pln("Thread1 starts execution of d1() method");
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{}
s.o.pln("Thread1 trying to call B's last() method");
b.last();
}
public synchronized void last()
{
s.o.pln("in A this is last() method");
}
}

class B{

public synchronized void d2(A a)


{
s.o.pln("Thread2 starts execution of d2() method");
try
{
Thread.sleep(2000);
}
catch(InterruptedException ie)
{}
s.o.pln("Thread2 trying to call A's last() method");
a.last();
}
public synchronized void last()
{
s.o.pln("in B this is last() method");
}
}

class MyThread extends Thread


{
A a=new A();
B b=new B();
public void m1()
{
this.start();
a.d1(b);
}
public void run()
{
b.d2(a);
}

public static void main(String[] args)


{
Mythread t=new MyThread();
t.m1();
}
}

You might also like