Showing posts with label Short notes on Thread. Show all posts
Showing posts with label Short notes on Thread. Show all posts

Thursday, February 11, 2010

Short notes on Thread

Thread:

A Thread is a path of execution of a program. A thread is a sequence of instructions that executed in a define unique flow of control.

SingleThread: A process is made up of one thread.

MultiThread: A process is made up of two or more thread.

Multitasking: It is a ability to do two or more tasks at a same time.


Create a Thread

-> extends Thread class
-> implements Runnable interface (its to be more useful because in big projects super class to be reserved one)

Process based:

It enables a computer to create more process concurrently. Each process having separate memory address location. So switches from one process to another , processor have face more overloads.

Thread based:

A program cotains more threads , it can do more tasks simultaneusly.

A processor switches from one thread to another with fewer overloads. It is also called as Light process.

Advantage:

  1. Improved performance

  2. Minimized system resource usage.

  3. Simultaneusly to use multiple application.

  4. Program structure simplification.

DisAdvantage:

Race condition: When two or more threads try to access the same variable atleast one thread should to write that variable before to access. Its arised because of lack of synchronization.

DeadLock: When two threads are waiting for each other for complete their operation before complete their individual actions.

Lock-starvation: While execution of thread postponed because of that low priority. Java runtime environment executes the thread based on priority. Because CPU executes one thread at a time. Thread priority value 1-10.

Life Cycle:

1.New: While thread initialized it will enter to init state. After we should call start() method, Otherwise it will cause IllegalThreadStateException.

2.Runnable: Once start method called then it will enter to runnable state. Start method allocate each thread resource and sheduldes it ,then it will call run() method.

3.NotRunnable: 3 ways

-> sleep() - wait for specified time.

-> wait() - wait until notify.

-> Blocked by another thread – Blocked thread while I/O opeartion.

4.Dead: if run method completed or thread object to be asign to null then its enter to this state.

Synchronization: Used to avoid racecondition or deadLock effects . Synchronization means serializing the threads. It allows to execute one thread at a time.