java multithreading
We can define java multithreading in the following two ways:-
- By extending Thread class
- By implementing Runable interface
1. By extending Thread class:-
example:-
class MyThread extends Thread
{
public void run ()//This for run method will be executed by child thread
{
for(int i=0;i<10;i++)
{
System.out.println("Child Thread");
}
}
}
class ThreadDemo
{
public static void main(String [] args)
{
MyThread t =new MyThread();
t.start();// starting of thread
for(int i=0;i<10;i++)
{
System.out.println("Main Thread");//This for Loop will be executed by main thread
}
}
}
run method:-
run method present is thread class and it has an empty implementation. child thread is responsible for executing run method. So we have to override the thread class run method in our java program. If we don't override run method then it's super class means thread class run method will be called and it has empty implementation so no output will be produced.
thread scheduler:-
In the above example, thread scheduler is responsible for scheduling thread.
- If multiple threads are waiting to get the chance of execution then in which order thread will be executed is decide by thread scheduler.
- We can't except exact algorithm followed thread scheduler, it is varied from JVM to JVM. Hence we can't tell exact output.
Possible outputs are:-
possibility 1
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
possibility 2
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
child thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
main thread
Possibility 3
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
main thread
child thread
No comments:
Post a Comment
Be the first to comment!
Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.
Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
Regards,
JavaByChetan
Back To Home