zondag 20 maart 2011

[Java] Basics of Threading

Hi, this is the first part of the Threading chapter of my series of tutorials.
This will be a small part, since it'll only tell you the basics principles on how to create multiple threads of one class. The date of when the new tutorials are coming out is still not decided. Quite some projects are on my mind at this very moment, so I can't promise anything.

definition

threads are parts of program that run in competition at the same time. An example of multithreading is the GC.



states

[Image: java_thread.jpg]

  • new state
    The thread has just been created
  • runnable state
    run() method is activated
  • waiting state
    part of the code can't be executed yet
    wait() gets activated.
    will be back at the runnable state as soon as something invokes notify()
  • timed waiting state
    waiting until the sleep() interval is finished
  • terminated state
    its job is done.
  • blocked state
    The thread can't fulfill its job (due to i-o call f.ex)

priorities



Every thread has a priority.

Code:
Thread.MIN_PRIORITY
Thread.NORM_PRIORITY
Thread.MAX_PRIORITY
If two threads have the same priority, timeslicing is used. Which means that they both get some quantumtime from the processor.

creation and execution of threads
We will use the runnable interface to create a thread.

this is the PrintTask thread class.


Code:
PrintTask implements Runnable
    {
         private int sleepTime; // random sleeptime
         private String threadName; // name of the thread
         private static Random generator = new Random();
         public PrintTask( String name )    {       // geef de thread een naam            threadName = name;            
           // random sleeptime between 0 and 5 seconds  
           sleepTime = generator.nextInt( 5000 );
        } // end PrintTask constructor

        //the run method will always be executed when the thread starts
        public void run() {   
            try              
               {      
                 System.out.printf( "%s going to sleep for %d \n", threadName, sleepTime );                   
                  Thread.sleep( sleepTime );   
                } // end try           
           catch ( InterruptedException exception )   
                {      
                   exception.printStackTrace();   
                } // end catch                 
          System.out.printf( "%s done sleeping\n", threadName );   }
} // einde klasse PrintTask

Executing them with a thread pool (executors)


Code:
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class RunnableTester
{
   public static void main( String[] args )
   {
      // creation of the 3 runnables
      PrintTask task1 = new PrintTask( "thread1" );
      PrintTask task2 = new PrintTask( "thread2" );
      PrintTask task3 = new PrintTask( "thread3" );
      System.out.println( "Starting threads" );
      // creating a thread pool with 3 fixed threads
      ExecutorService threadExecutor = Executors. newFixedThreadPool(3);

      threadExecutor.execute( task1 );

      threadExecutor.execute( task2 );
      threadExecutor.execute( task3 );

      threadExecutor.shutdown(); // shutting down the threadpool
  
      System.out.println( "Threads started, main ends\n" );
   } // end main
} // end class RunnableTester

Shared Objects

Sometimes, it's necessary to share objects within our threads. To avoid curruption or outdated resources, we use synchronisation, keywords in this field are 
Lock and ReentrantLock.
In my next chapter, I'll explain how to use these Locks to avoid problems.
As a bonus, I'll add a design pattern to the next tutorial, the singleton pattern

Geen opmerkingen:

Een reactie posten