THREADS
By Santhoshi Jyotsna Jaideep S
MULTITASKING VS MULTITHREADING
Similarities
Performing multiple tasks concurrently. OS dependent for time slicing and context switching Optimum utilization of CPU resources.
Differences
In multitasking require n processes for n jobs. In multithreading require one process for n jobs.
PROCESS VS THREADS
Threads are leightweight processes. One process cannot access another process but threads can share data between each other. JVM (or) OS (or) both decides which thread would run at given point of time. Single core processor runs one thread whereas multi core processor runs multiple threads. Threads take job and execute in parallel and overall task finishes faster. Ex : Google docs we used day before yesterday.
USING THREADS
Two ways
Implementing the Runnable interface, Extending the Thread class, itself.
If extends from one class we cannot extend from another class but we can implement interface even though we extend a class. Always preferred to implement runnable than to extend thread class.
LIFE CYCLE OF A THREAD
New Runnable Dead
Lock Sleep Running I/O blocked
METHODS
public static void yield() public static void sleep(long millisec) public static void join() (Different parameters) public static void run() public static void start()
PRIORITY
Thread priority is a number used by thread scheduler to decide the preferences in allocating CPU cycles to the threads. In [Link] class, there are constants that represents the priority
MIN_PRIORITY (1) MAX_PRIORITY (10) NORM_PRIORITY (5) Syntax : [Link](Thread,MAX_PRIORITY) or [Link](8)
DAEMON THREAD
It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. Its life depends on user threads. Its a low priority thread.
Note : If you want to make a user thread as daemon thread, it must not be started otherwise it will through illegalThreadStateeException
SYNCHRONIZED METHODS
Whenever multiple threads are acting upon the same shared resource there is a chance of data inconsistency and we say multi threaded apps are not thread safe. Levels of synchronization
Method level synchronization Block level synchronization
DEAD LOCK
When each thread is waiting for other threads to release the lock before it can continue. But neither thread will release the lock until it finishes this situation is known as dead lock.
Thread 1 Thread 2
AVOIDING DEAD LOCK
Example program Call suspend within run(), outside the synchronization method.
INTERTHREAD COMMUNICATION
Threads communicate one another using three methods of [Link] class. All these three methods can be called only in the synchronized context.
wait() notify() notifyAll()