Tuesday, April 2, 2013

Multithreading in java

Multithreading is a  process of executing multiple threads simultaneously. Thread is basically a lightweight subprocess , a smallest  unit of processing .

Multithreading is  mostly  used games, animation etc.



Extending the Thread Class
The steps for creating a thread by using the fi rst mechanism are:
 1. Create a class by extending the Thread class and override the run() method:
class MyThread extends Thread {
 public void run() {
 // thread body of execution
 }
 }
 2. Create a thread object:
MyThread thr1 = new MyThread();
 3. Start Execution of created thread:
thr1.start();



THREAD LIFE CYCLE
The life cycle of threads in Java is very similar to the life cycle of processes running in an operating system.
During its life cycle the thread moves from one state to another depending on the operation performed by it
or performed on it as illustrated in Fig. 14.4. A Java thread can be in one of the following states:
∑ NEW
 A thread that is just instantiated is in new state. When a start() method is invoked, the thread
moves to the ready state from which it is automatically moved to runnable state by the thread
scheduler.
∑ RUNNABLE (ready running)
 A thread executing in the JVM is in running state.
∑ BLOCKED
 A thread that is blocked waiting for a monitor lock is in this state. This can also occur when a thread
performs an I/O operation and moves to next (runnable) state.
∑ WAITING
 A thread that is waiting indefi nitely for another thread to perform a particular action is in this state.
∑ TIMED_WAITING (sleeping)
 A thread that is waiting for another thread to perform an action for up to a specifi ed waiting time is in
this state.

No comments:

Post a Comment