Tips and Study Notes for Sun Certified Java2 Programmer's Exam









Section 7 Threads


Two ways to create a new thread:

1. Have a class implement the Runnable interface. Ex:

class X implements Runnable 
{ 
  public void run()  //must implement this method.
  {
    ...
  }
}
Now, create a Thread object :
 X obj = new X(); //Not a new thread yet. 
 Thread t = new Thread( obj );  //This creates a new Thread. It's not started yet.


2. Have a class extend from Thread class. Ex:

class X extends Thread 
{ 
  public void run(){ ... } //should implement this method to do something useful.
}
Now, create a Thread object :
Thread t = new X();
 

Points to remember:




Methods that will definitely stop/pause a running thread:

sleep() : Does not release the locks (if any).
wait() : should have the lock before calling this method. It releases the lock and waits till somebody calls a notify/notifyAll.
stop() : releases all the locks. Deprecated.
suspend() : DOES NOT release any locks. Deprecated.
 
 

Methods that MAY or MAY NOT stop/pause a running thread:

yield() : If there are no threads of the same priority, this call is ignored
setPriority() : even if you lower the priority, the OS may not preempt this thread.
notify/notifyAll() : These methods simply release the locks and other thread which are waiting on them become "read to run". But CPU may or may not schedule them.
 

Points to note :
join() : It will pause the current thread till the thread on which it has called join, dies.
 


Important Facts:
  This is very important topic which you should read from any good book like Thinking in Java.

Points to remember: