Oopj Unit4
Oopj Unit4
Lifecycle of a thread:
A thread can be in one of the following states
1.Newborn state
2.Runnable state
3.Running state
4.Blocked state
1.Newborn state
When an object of the thread class is created then it is said to be a New born state.
2.Runnable state
When the thread is in a queue waiting for the cpu then it is said to be in Runnable state.
3.Running state
When the thread is being executed by the cpu then it is said to be Running state.
4. Blocked state
A thread enters into blocked state if one of the following methods are called
1.sleep ()
2.wait ()
3.suspend ()
5.Dead state
Once the code of the thread is executed then it enters into dead state from the blocked state if a
thread wants to enter into running state then the following methods are called
1.notify ()
2.resume ()
Creation of threads:
A thread can be created using two methods
1.By extending the thread class
2.By implementing the Runnable interface
Assining priorities to threads:
Set priority () method is used to assign priority to the threads.
MIN-PRIORITY-1
NORM- PRIORITY-5 constants
MAX- PRIORITY-10
Types of threads:
Threads are classified into two types
1.user threads
2.Daemon threads
User threads
The threads which are created by the user (or)programmer are called user threads.
Daemon threads
The threads which are executing in the background process are called Daemon threads.
SYNCHRONIZATION:
Synchronization refers to the co-operation and co-ordination among multiple processes in
accessing a single resource.
Synchronisation can be achieved in java using three methods:
1.synchronized block
2.synchronized method
3.static block.
1. synchronized block:
synchronised
{
}
2. synchronized method:
public synchronised void run ()
{
}
3. static block:
static
{
}
CLASSICAL PROBLEMS OF SYNCHRONISATION:
1.producer-consumer problem
2.Reader- writers problem
3.Dining philosopher's problem
}
Class Sample 3 extends Thread
{
Public void run ()
{
While(true)
{
System.out.print("\n\n\t WELCOME");
try
{
Sleep (3000);
}
Catch (Exception e3)
{
System.out.print(e3);
}
}
}
}
Class Sampledemo
{
Public static void main (String args[]) throws Exception
{
Sample s1= new sample1();
Sample s2=new sample2();
Sample s3=new sample3();
s1.start ();
s2.start ();
s3.start ();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20