Hi Friends !! Today I am talking about one of the most important topic of
java…which is MULTITHREADING.
MULTITHREADING
To see this
topic, the very first ques. strike to our mind is that….What is
multithreading??????
A
multithread program contains two or more parts that can run concurrently….these
such parts of program is known as thread.
Each
thread defines a separate part of execution.So,we an say Multithreading is same as or a type of Multitasking….
Multithreading enables you to write very efficient program that make maximum use of CPU, bcoz idle time of CPU kept to a minimum.
Thread life cycle:
Threads
exit in several stage:
Running:It means it can be ready to run as
soon as it gets CPU time.
Suspended:It means temporarily suspend the
activity..
Resume: it means suspended thread allowing
it to pick up where it left off.
Block: a thread is waiting for a resource.
- At any time,a thread can be terminated,which halts its execution immediately.Once terminated, a thread cannot be resumed.
- A main thread is declared in the program ,which begins running immediately when the Java program starts up…
This
main thread is mainly use for 2 reason:
1) It is the thread from which other
“child ”threads will be spawned.
2) Often it must be the last thread to
finish execution bcoz it performs various shutdown actions….
5 phases of a thread
can be explain through diagram as:=>
these
are the methods through which we go from one state to another state…
Let us see an simple
example of multithreading:
Class
abc extends Thread
{
public
void run()
{for(int
x=1;x<=5;x++)
{
System.out.println(x);
}
}
}
Class
def extends Thread
{
public
void run()
{for(int
y=1;y<=5;y++)
{
System.out.println(y);
}
}
}
Class
ghi extends Thread
{
public
void run()
{for(int
z=1;z<=5;z++)
{
System.out.println(z);
}
}
}
Class
pqr
{
public
static void main(String[] args)
{
abc
a1=new abc();
a1.start();
def
d1=new def();
d1.start();
ghi
g1=new ghi();
g1.start();
}
}
output:
1,2,3,4,5
Another example of
multithreading in which we use the methods- yeild(),sleep(),stop()
Class
abc extends Thread
{
public
void run()
{for(int
x=1;x<=5;x++)
{
if(x==1)
yield();
System.out.println(x);
}
}
}
Class
def extends Thread
{
public
void run()
{for(int
y=1;y<=5;y++)
{
System.out.println(y);
if(y==3)
stop();
}
}
}
Class
ghi extends Thread
{
public
void run()
{for(int
z=1;z<=5;z++)
{
System.out.println(z);
if(z==1)
try{
sleep(1000);
}
catch(Exception
e)
{System.out.println(“exception”);
}
}
}
}
Class
pqr
{
public
static void main(String[] args)
{
abc
a1=new abc();
a1.start();
def
d1=new def();
d1.start();
ghi
g1=new ghi();
g1.start();
}
}
If still You have any query regarding to this article then please post your comment i will 100% reply back you…..Thanks……:)
0 comments:
Post a Comment
Hey thanax alot to comment i will revert you back soon...