Difference between revisions of "Threads"

From Suhrid.net Wiki
Jump to navigationJump to search
 
Line 1: Line 1:
 
* Think of Thread as the "worker" and Runnable as the job.
 
* Think of Thread as the "worker" and Runnable as the job.
 
* Define work to be done in a class that implements Runnable.
 
* Define work to be done in a class that implements Runnable.
* Instantiate the thread using the runnable object and then start() it.
+
* Instantiate the thread using the runnable object. (Thread is in the new state)
 +
* Then start() it. (Thread moves to the runnable state, eligible to run, perhaps waiting for the scheduler to run it)
  
 
<syntaxhighlight lang="java5">
 
<syntaxhighlight lang="java5">
Line 12: Line 13:
 
Job j = new Job();
 
Job j = new Job();
 
Thread t = new Thread(j);
 
Thread t = new Thread(j);
 
 
t.start();
 
t.start();
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
* When thread actually runs it is in the running state.
 +
* The thread can also go into waiting/blocked/sleeping state. e.g. waiting for an IO Resource such as a packet to arrive. In other words it is NOT ''runnable''.
 +
* Once run() completes the Thread goes to the dead state. You cannot call start() again on it. Of course, the thread object itself can still be used.

Revision as of 23:21, 8 June 2011

  • Think of Thread as the "worker" and Runnable as the job.
  • Define work to be done in a class that implements Runnable.
  • Instantiate the thread using the runnable object. (Thread is in the new state)
  • Then start() it. (Thread moves to the runnable state, eligible to run, perhaps waiting for the scheduler to run it)
class Job implements Runnable {
     public void run() {
         //work to be performed in  a separate thread.
     }
}

Job j = new Job();
Thread t = new Thread(j);
t.start();
  • When thread actually runs it is in the running state.
  • The thread can also go into waiting/blocked/sleeping state. e.g. waiting for an IO Resource such as a packet to arrive. In other words it is NOT runnable.
  • Once run() completes the Thread goes to the dead state. You cannot call start() again on it. Of course, the thread object itself can still be used.