You are here:

Java/thread execution in java

Advertisement


Question
Hello sir!
i know that due to multithreading cpu idle time is reduced.
when cpu is free or waiting for  input or output then it starts execution of another thread.
I am expressing my doubts based on below programme.
------------------------------------------------------------------
class thread6
{
public static void main(String args[])
{
Thread count1=new Thread(new CountDownEven());

Thread t=Thread.currentThread();
count1.start();


for(int i=11;i<=20;i=i+2)
{
System.out.println(t.getName()+"----"+i);

}

}
}
class CountDownEven implements Runnable
{
public void run()
{
Thread t=Thread.currentThread();
for(int i=0;i<10;i=i+2)
{
System.out.println(t.getName()+"----"+i);

}
}
}
------------------------------------------------------------------
my doubts:
1)why the above programme gives different outputs.?
2)Execution starts from main thread. in main thread i have written for loop.Before that i wrote count1.start,which starts execution of another thread.but some times for loop in main thread gets executed before another thread.why ?how can i understand this ?
3)when control moves from one thread to another thread?
4) can you tell me execution of threads and behaviour of thread scheduler?  or can you give some website details?
-----------------------------------------------------------------
outputs of above programme:
out put1
------------:
Thread-0----0
main----11
Thread-0----2
Thread-0----4
Thread-0----6
main----13
main----15
main----17
main----19
Thread-0----8

output2:
------------
Thread-0----0
Thread-0----2
Thread-0----4
main----11
main----13
main----15
Thread-0----6
Thread-0----8
main----17
main----19

output3:
---------------
main----11
Thread-0----0
Thread-0----2
main----13
main----15
main----17
main----19
Thread-0----4
Thread-0----6
Thread-0----8
------------------------------------------------------------------

Answer
Hi,

Your output works that way because you are dealing with threads. In thread programming, it is designed to be doing more than one thing at a time. So, only the scheduler determines which thread gets executed and when but if you want to be specific about which one runs first and which one runs next, then you have to use the setPriority() method to do that. I would suggest you search online for materials relating to schedulers.

Best of luck

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


henry joe

Expertise

I can confidently answer questions relating to JSE and JEE6 . Please no questions on JME.

Experience

I am experienced in JSE and JEE6

Education/Credentials
I am a BSEng graduate

©2016 About.com. All rights reserved.