Multi Threading
Performing
multiple tasks at a time is called
Multitasking. This is possible with the
Threads concept in JAVA. Java is also
known as multithreaded programming language .Thread is a light weight process
which executes one task at a time .In between tasks it takes gap and will do
another task. Threads are executed concurrently.
In
this diagram, two threads are being executed having more than one task. The
task of each thread is switched to the task of another thread.
By
default JVM creates two common threads known as
1. Main thread: ---Is responsible to
execute the main logic present in java application.
2. Garbage Collector thread:--to delete
unreferenced objects which are created by main thread.
This GC thread is also known as DEMON thread.
Demon Thread:-- which is a low priority thread
.It provides help to main thread.
Thread
priority:--every thread has its own priority.These are available from 1 to 10.
The
thread priority is available in java.lang.Thread Class as below
1. MIN_PRIORITY=1
2. NORM_PRIORITY=5
3. MAX_PRIORITY=10
We
can create user-defined threads also in two ways .
ü Extending
from Thread class
ü Implementing
from Runnable interface
If
we extend our class with Thread class then our Class objects acts like a Thread class objects . Then it displays
the details as like Thread class details.The advantages of using threads are:
Ø Can
be created faster.
Ø Inter
process communication is faster.
Ø Context
switching is faster.
Ø Max
use of CPU.
Thread States
There
are four states associated with a thread namely: new, runnable, dead and
blocked.
1. New:--Implies
that the Thread object has been created but it has not started running.
It requires the START() to start it.
2.
Runnable:--in this the thread is
ready for execution.
3.
Running:--in this the thread is
executing the process .It contains set of instructions and it is called
automatically after start ().
4.
Waiting: - in this the thread is
going to waiting state .
5.
Blocked:--The THREAD could be run
but there is something that prevents it.
6.
Dead ():--after execution finished
the thread going to die. not suggest able.
Thread
class Methods
1.void start()
|
This method causes
the thread to begin excution.
|
2.void run()
|
run() cosists of
user-defined logic which is executed
When the thread execution is started.
|
3.void setName(String
name)
|
This method sets the
name to a thread.
|
4.setPriority(int
priority)
|
sets the priority for
the thread.
|
5.void
setDeamon(Boolean val)
|
This sets the thread
to Demon thread.
|
6.String getName()
|
Returns the THREAD
name.
|
7.int getpriority()
|
returns the priority.
|
8.Boolean isDemon()
|
It checks wheather it
is a demon Thread or not.
|
9.void interrupt()
|
It interrupts the
thread excecution.
|
10.void join()
|
stops one
execution,excutes another and comeback.
|
11.void suspend()
|
will suspends the
thread execution.
|
12.void resume()
|
continued after
suspend().
|
13.void sleep(long
mc):--
Void sleep(long ms,int
n)
|
Sends to sleeping
state
|
Along
with these methods 5 methods are inherited fromjava.lang.object are:---
void
wait ()
void
wait (long ms)
void
wait (long ms, int ns)
These are used to send a thread to waiting
state.
void
notify()
void
notifyAll()
notifies
after waiting time is over.
1.
When we call start(), internally it calls run().
2.To
run run() compulsory we need to call
start().
3.If
we use start() two times then it runs randomly,
No
need of in the same order,will run in any order.We can set the priority of a
thread.
//If
we create a object to a class ,this we call it as a thread.
Ex1:---
class ThEx extends Thread{
public static void main(String[] args) {
ThEx t1=new ThEx();
ThEx t2= new ThEx();
t1.start(); t2.start();
}
public void run(){
for(int i=0;i<10;i++){
System.out.println(i);
}
} }
Note : - by default
priority is 5
Ex.2.
class ThEx1 extends Thread{
public static void main(String[] args) {
ThEx1 t1=new ThEx1();
t1.setPriority(5);
t1.start();
System.out.println("The
t1 priority " +t1.getPriority());
}
public void run(){
System.out.println(“am in run method ”);
}
}
}
//creating threads in different class
//if
multiple threads r running then it gives prioarity to main thread only
Ex.3.
class
A extends Thread{
public void run(){
for(int i=10;i>0;i--){
show();
System.out.println(i);
}
}
void show(){
System.out.println("am in
show method");
}
}
class
B extends Thread{
public void run(){
for(int i=0;i<10;i++){
System.out.println(i);
}
}
}
class
ThEx2{
public static void main(String[] args) {
A a=new A();
B b=new B();
a.start(); b.start();
for(int h=90;h<100;h++){
System.out.println(h);
}
}
}
Ex.4.
class
mythread extends Thread{
public void run(){
try{
for(int i=1;i<=50;i++) {
System.out.println(i+"\t");
Thread.sleep(1000);
}
}
catch (Exception e){
System.out.println("interupted");
}
}
}
public class FirstthreadProgram{
public static void
main(String[] args) {
long time1,time2;
time1=System.currentTimeMillis();
mythread t1=new
mythread();
t1.run();
t1.start();
try{
for(int
i=50;i>=1;i--){
System.out.println(i+"\t");
Thread.sleep(1000);
}
}
catch (Exception e){
System.out.println("inturrupted");
}
time2=System.currentTimeMillis();
System.out.println("\ntime
taken to execute both the tasks:"+(time2+time1)/10000+"secs");
}
}
Ex.5.
public
class joinDemo extends Thread{
joinDemo(String name){
super(name);
}
public void run(){
System.out.println(getName()+"started");
try{
for(int i=0;i<=4;i++){
System.out.println(getName()+":"+i+"\t");
}}
catch (Exception e){
System.out.println("inturrupted");
} }
public static void main(String[] args) {
joinDemo jd1=new
joinDemo("child1");
joinDemo jd2=new
joinDemo("child2");
jd1.start();
jd2.start();
try{
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i+"\t");
if(i==5){
try{
jd1.join();
}catch (Exception e){
System.out.println(e);
}
}
} }
catch (Exception e){
System.out.println("inturrupted");
}
}
}
void
setName(String name): -- We can SET the name. can change the default name to
required name.
String
getName():-- Gets the name.
Ex.6:----
Runnable
Interface: ---
Runnable
is an interface. So we use implements key word for runnable interface. And
Thread is a implemented subclass for Runnable class and which is overring
the run() method . If we implements
means compulsory we need to overwrite run().This will be called through
start().
So hierarchy is as
follows:
Runnble(interface)
Thread
(subclass of runnable interface)
//creating
threads by implementing runnable interface
class
NewThread implements Runnable {
Thread th;
NewThread() {
//created a new thread
th=new Thread(this,"our
own thread");
System.out.println("child
thread,ourown thread:"+th);
//th.start();
}
//this is entry point of the thread
public void run(){
try{
for(int i=5;i>=0;i--){
System.out.println("child
thread:"+i);
Thread.sleep(1000);
}
}catch (InterruptedException
e){
System.out.println("child
interrupted");
}//catch
}//run
}//class
public class
RunnableDemo{
public static void main(String[] args) {
new NewThread().th.start();
try{
for(int i=5;i>=0;i--){
System.out.println("Main
Thread:"+i);
Thread.sleep(1000);
}
}catch
(InterruptedException e){
System.out.println("Main Interrupted");
}//catch
System.out.println("Main
Thread exited!");
}
}
Thread Synchrinization
Consider an example ,If 3 requests are going to a printer at same point of time,it may not work and leads to dead lock
occurs.
In
the same way if a resource is accessed by multiple threads at a time it leads
to deadlock . In this case the resource
may be corrupted or cant produce the required output. To resolve this
problem there is a Synchrinization Technique in java.This checks for priority.
But
if all the priorities are one and the same loke 5 then checks FirstInFirstOut,Round
Robin Technique..etc to execute the threads.
This technique is implemented with
“ synchronized ” keyword in java.
Synchrinization technique is used to resolve
the deadlock situation arised when we are Dealing with Multiple Threads.
//using
class with synchronized method
class
SMethod {
synchronized void display(String msg){
try{
System.out.println("*******"+msg);
Thread.sleep(1500);
}catch (Exception e){ }
System.out.println("***********");
}
}
class
SMCaller implements Runnable{
String msg;
SMethod
sm;
Thread
th;
public
SMCaller(SMethod sm,String s){
this.sm=sm; msg=s;
th=new Thread(this);
th.start();
}
public
void run(){
sm.display(msg);
}//end run
}//end
class
public
class SynchrinizationDemo{
public static void main(String[] args) {
SMethod sm=new SMethod ();
SMCaller ob1=new
SMCaller(sm," good morning ");
SMCaller ob2=new SMCaller(sm,"good
afternoon ");
SMCaller ob3=new
SMCaller(sm," good evening ");
}//main
}//end class
Output:
*********good
morning********
*********good afternoon********
*********good
evening********
No comments:
Post a Comment