Programmierpraktikum




Claudius Gros, SS2012

Institut für theoretische Physik
Goethe-University Frankfurt a.M.

Processes and Threads

processes vs. threads



processes

threads

parallelization

sleeping

import java.util.*;

public class SleepingDemo {
  public static void main(String args[])
        throws InterruptedException             // needed when working with threads
  {
  long startTime = System.currentTimeMillis();  // current time in milli seconds
  for (int i = 0; i< 5; i++) 
    {
    Thread.sleep(2000);                         // pause current thread for 2 seconds
    System.out.printf("time since start: %5d ms\n",
                      System.currentTimeMillis()-startTime);
    }
  }  // end of  main()
}    // end of SleepingDemo

runnable classes

threads and interrupts

import java.util.*;

public class ThreadDemo {
  public static void main(String args[])
        throws InterruptedException           // needed when working with threads
  {
  long startTime = System.currentTimeMillis();

  SomeOperations some = new SomeOperations(); // class instantiation
  Thread t = new Thread(some);                // create new thread
  t.start();                                  // start some.run()

  for (int i = 0; i < 6; i++) 
    {
    Thread.sleep(2000);                       // pause thread of main()
    System.out.printf("   time since start: %5d ms\n",
            System.currentTimeMillis()-startTime);
    System.out.printf("nOperations/1000000: %5d\n",
                  some.nOperations/1000000);

    if (i==3)                               // thread would run ad infinitum
      t.interrupt();                        // if not interupted
    }
    
  }  // end of ThreadDemo.main()
}    // end of class ThreadDemo

// *** **************
// *** runnable class
// *** **************

class SomeOperations implements Runnable {
  double number = 1.0;
  public long nOperations = 0;

  public void run()              // every runnable class needs 
  {                              // this member function
  long temp;
  while (!Thread.interrupted())  // infinite loop!
    {
    nOperations++;
    number = number * (1.0+1.0/nOperations);
    }
  System.out.printf("\n %s \n\n","I have been interrupted, stopping now");
  }  // end of SomeOperations.run()
}    // end of class SomeOperations

exercise: threads

large number of threads on a single processor

Write a program generating a large number of threads and measuring the resulting computational performance.

the Java virtual maschine (JVM)



platform independent computing

garbage collection (GC)