Sunday, April 11, 2010

Java Concurrency/Threads

Process vs Thread
Process - is a running program that runs independently from other processes. It has its own address space and cannot directly access resources of other processes. Each process can have one or more threads.

Thread - is sometimes called lightweight process. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads share the process's resources, including memory and open files.

2 ways to define a Thread:
  1. implement Runnable interface
    - more general, can have many superclass
    - starting: (new Thread(new HelloRunnable())).start();
  2. extend Thread class (Thread class itself implements Runnable)
    - simpler but limited
    - starting: (new HelloThread()).start();

Thread methods:
  • public void run() - the only method coming from Runnable
  • public void start() - calls the run() method, can only be called once
  • public static void sleep(long millis)/(long millis, int nanos) throws InterruptedException - suspend execution for a specified period
    - time is not guaranteed
    - can be interrupted
  • public void interrupt() - indicates that thread should stop
  • public static boolean interrupted() - interrupted status is cleared
  • public boolean isInterrupted() - has no effect on interrupted status
  • public final void stop()/suspend()/resume() - deprecated

ObjectThread
notify
notifyAll
wait
sleep
yield


Source: http://java.sun.com/docs/books/tutorial/essential/index.html
http://www.vogella.de/articles/JavaConcurrency/article.html

No comments:

Post a Comment