I want to know how many threads can be run on a CPU for a single application at the same time?
I same a simple like:
import java.awt.SystemColor;
import java.util.Date;
public class Threadcall {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("--------------------------");
System.out.println(Runtime.getRuntime().availableProcessors());
System.out.println("--------------------------");
for (int i = 0; i < 5; i++) {
new samplethread(i);
}
// create a new thread
//samplethread1.run();
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i + "\t" + new Date());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
public class samplethread implements Runnable {
Thread t;
samplethread(int i) {
// Create a new, second thread
t = new Thread(this, Integer.toString(i));
System.out.println("Child thread Creation NO: " + i + "\t" + t.getName());
t.start(); // Start the thread
// t.run();
}
@Override
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread Run: " + i + "\t" + t.getName() + "\t" + new Date());
// Let the thread sleep for a while.
System.out.println("****************************");
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
It shows the output like:
Processor Number: 2
Main Thread: 3 Sun May 26 19:23:19 IST 2013
Child Thread Run: 1 2 Sun May 26 19:23:19 IST 2013
Child Thread Run: 1 1 Sun May 26 19:23:19 IST 2013
Child Thread Run: 1 3 Sun May 26 19:23:19 IST 2013
Child Thread Run: 1 0 Sun May 26 19:23:19 IST 2013
Child Thread Run: 1 4 Sun May 26 19:23:19 IST 2013
From the output we can see that at the same moment five threads can execute (I even do print the result in milliseconds)..........I have two processor which is reported in the programme.
How is this possible?
Because one thread can run in only one CPU at a time but it shows that five threads run at the same time.
Is there any way to show that only one thread can ran in one CPU at the same time.......
If I modify my code like:
t.start();
t.join();
Then it shows the output like:
Child thread Creation NO: 99 99 Child Thread Run: 5 99 Sun May 26 21:02:32 IST 2013
Child Thread Run: 4 99 Sun May 26 21:02:32 IST 2013
Child Thread Run: 3 99 Sun May 26 21:02:33 IST 2013
Child Thread Run: 2 99 Sun May 26 21:02:33 IST 2013
Child Thread Run: 1 99 Sun May 26 21:02:34 IST 2013
So how is it possible that if I add a simple line in the code then it shows that only two threads can access two processors?