Wednesday, January 19, 2011

Java's Thread Class

Thread is a seamless execution of concurrent processes. This allows maximized use of CPU time and its resources as segments of processes are done synchronously or asynchronously.

Threads can be created through extending Thread class and using Runnable interface.  A thread can be in one of the following states:

  • New - a thread is yet to be created
  • Ready - a thread waits for execution
  • Running - a thread on execution
  • Inactive - thread is blocked for period of time or indefinitely
  • Terminated, Dead/Finished - if a thread has completed or forced to stop.
A sample thread  is shown below.

[+/-] show/hide

class MyThread extends Thread{
MyThread(String message)

public void run(){
for ( int x =1;x<=3;x++) System.out.println(getName()); } } public class ThreadQuiz1{ public static void main(String args[]){ MyThread greet1 = new MyThread("Hello"); MyThread greet2 = new MyThread("Hi"); greet1.start(); greet2.start(); } }

No comments: