I'm really curious on how threads execute when the JVM is given multiple processors. So, I designed a very simple application that starts a second thread off of the main at the same time and executes. Both threads do the same thing and sleep at the same time. The overhead question for me here was, "does the JVM recognize and work with multiple processors on thread execution? Will it use multiple cores to execute multiple threads simultaneously?"
The results were very interesting and not exactly what I expected. Rather than try to explain them to you or post screenshots, I'll give you the source code for you to copy, and run it under TWO scenarios.
First, (and this only applies to those running a machine with more than one core) just run the program and observe the results of how the threads execute.
Second, run the program, but do not hit a key yet at the scanner line to start it. Open Windows Task Manager (or the equivalent on your platform) and change the processor affinity so that the Java machine process has only ONE processor to work with. Observe those results.
If any of you would care to explain to me how Java works with multiple cores, and if it works concurrently, please do so. Thanks!
import java.util.Scanner; class ThreadTest { public void startThreads() { Scanner sc = new Scanner(System.in); sc.nextLine(); Thread t = new Thread(new SecondThread()); t.start(); for(int i=50;i>0;i--) { System.out.println("Main thread working"); try { Thread.sleep(1000); } catch(InterruptedException e) {} } System.out.println("Main is done"); } class SecondThread implements Runnable { public void run() { for(int i=50;i>0;i--) { System.out.println("Second thread is working"); try { Thread.sleep(1000); } catch(InterruptedException e) {} } System.out.println("Second thread is done"); } } public static void main(String[] args) { ThreadTest tt = new ThreadTest(); tt.startThreads(); } }