title: How to measures the speed of a context switch on a UNIX/Linux system using Java program
body: <p>I need to measure thread context switching I write below program is that correct way please let me know and wanted to get update on this post.
  Any one can help.</p>
  
  <p>/**
  Below is the program which I am trying is this a correct way.
  */</p>
  
  <pre><code>public class JavaContextSwitch {
      final static Object ob = new Object();
      final static int numberOFThread=10;
      final static MyThread []threadArray =new MyThread[numberOFThread];
      public static void main(String args[]) throws InterruptedException{
  
          long mainThreadStart=System.nanoTime();
  
          for(int i=0;i&lt;numberOFThread;i++){
              threadArray[i]= new JavaContextSwitch.MyThread(numberOFThread);
              threadArray[i].setPriority(Thread.MAX_PRIORITY);
              threadArray[i].start();
              threadArray[i].join();
          }
          System.out.println("All Thread is relaase for job and witing ..");
          //Thread.currentThread().join();
  
          System.out.println("Waiting is over ");
          long endOfMainThread= System.nanoTime();
          System.out.println("Total time taken is "+(endOfMainThread-mainThreadStart));
          long sum=0;
          for(int i=0;i&lt;numberOFThread;i++){
              long timeTaken=  threadArray[i].timefinish-threadArray[i].startTime;
              System.out.println("Each thread running time "+timeTaken);
              sum=sum+timeTaken;
          }
          System.out.println("Total time taken by thread is "+sum);
          System.out.println("Average "+numberOFThread+" Taken "+(sum/numberOFThread)+" Time ");
          long timeForContextSwitch= (endOfMainThread-mainThreadStart)-sum;
          System.out.println(" Context switch time is "+timeForContextSwitch);
          System.out.println(" Average Context witching "+ (timeForContextSwitch/numberOFThread+1));
      }
  
      private static class MyThread extends Thread {
          public long startTime;
          public long timefinish;
          int cycle = 0;
  
          public MyThread(int cycle) {
              this.cycle = cycle;
          }
  
          public void run() {
              System.out.println(" Child thread started"+this.getId());
              startTime=System.nanoTime();
              // Child thread is busy to complete their job.
                  for (int i = 0; i &lt; cycle; i++) {
                  for (int j = 0; j &lt; 640 * 81; j++)
                      timefinish = System.nanoTime();
              }
                  System.out.println("I am done now "+this.getId());
          }
  
      }
  }
  </code></pre>