Lecture9 Java
Lecture9 Java
MULTI THREADING
Thread:
A thread represents a path to execute a group of statements by JVM. A thread is similar to a program
that has a single flow of control. It has a beginning, a body & an end and executes the statements
sequentially.
In every Java program, there is always a thread running internally. This thread is used by JVM to
execute the program statements. That thread is called “main”.
Multi-Threading:
Executing multiple tasks at a time is known as multi-threading. The processor executes multiple tasks
simultaneously for a specified time in Round–Rabin method.
Uses of threads:
Thread can be used for multiple purposes.
1. Threads are mainly used in server–side programs to serve the services to the multiple clients on
a network or Internet.
2. Threads are also used to create games and animations. Animation means moving the things
from one place to another place. In many games, generally we have to perform more than one
task simultaneously.
Creating a thread:
In every Java program, there is a main thread available already. We can also create our own threads in
a program. A new thread can be created in two ways.
1. By using the Thread class.
2. By using the Runnable interface.
Both the Thread class and Runnable interfaces are available in java.lang package.
Step 1: Define a class as a sub class to the Thread class as shown below.
step 2: Implement the run( ) method and declare it as public with no return value(void).
Syn: class MyThread extends Thread {
public void run( ) {
-----
----
}
}
In this run( ) method, we should write the group of statements for the particular task executed by the
thread.
Step 4: Call the start( ) method with sub class object to starts the thread execution.
Syn: mt.start( );
Ex:
class Even extends Thread {
int sp, ep;
Even(int a, int b) {
sp = a;
ep = b;
}
Odd(int a, int b) {
sp = a;
ep = b;
}
if ((i % 2) != 0) {
System.out.println("From Odd: " + i);
}
}
}
}
class ThreadUse {
public static void main(String args[]) throws IOException {
DataInputStream d = new DataInputStream(System.in);
int s, e;
System.out.println("Enter the starting point");
s = Integer.parseInt(d.readLine());
System.out.println("Enter the ending point");
e = Integer.parseInt(d.readLine());
Even e1 = new Even(s, e);
Odd o1 = new Odd(s, e);
e1.start();
o1.start();
}
}
Output:
Enter the starting point
1
Enter the ending point
5
From Even: 2
From Even: 4
From Odd: 1
From Odd: 3
From Odd: 5
Step 2: Implement the run( ) method and declare it as public with no return value(void).
Syn: class MyThread implements Runnable {
public void run( ) {
-----
----
}
}
In this run( ) method, we should write the code for the particular task executed by the thread.
Step 4: Create an object to the Thread class with implementation class object as parameter as shown
below.
Syn: Thread t1 = new Thread(mt);
Step 5: Call the start( ) method with Thread class object to starts the thread execution.
Syn: t1.start( );
Ex:
class Even implements Runnable {
int sp, ep;
Even(int a, int b) {
sp = a;
ep = b;
}
Odd(int a, int b) {
sp = a;
ep = b;
}
}
class RunnableThread {
public static void main(String args[]) throws IOException {
DataInputStream d = new DataInputStream(System.in);
int s, e;
System.out.println("Enter the starting point");
s = Integer.parseInt(d.readLine());
System.out.println("Enter the ending point");
e = Integer.parseInt(d.readLine());
Even e1 = new Even(s, e);
Odd o1 = new Odd(s, e);
Thread t1 = new Thread(e1);
Thread t2 = new Thread(o1);
t1.start();
t2.start();
}
}
Output:
Enter the starting point
1
Enter the ending point
5
From Even: 2
From Even: 4
From Odd: 1
From Odd: 3
From Odd: 5
2. start( ):-
This method is used to start the execution of a thread.
Syn: t.start( );
3. sleep(milliseconds ):-
This method is used to stop execution of a thread for a specified time.
Syn: t.sleep(1000 );
4. getName( ):-
This method is used to get the name of the thread.
Syn: String name=t.getName();
5. setName( ):-
This is used to set a new name to a thread.
Syn: t.setName(“new name”);
6. isAlive( ):-
This method is used to test whether a thread is still alive or not.
Syn: boolean b = t.isAlive( );
7. getPriority( ):-
This method is used to set the priority of a thread.
Syn: int n = t.getPriority( );
8. setPriority( ):-
This method is used to set the priority of a thread.
Syn: t.setPriority(number);
MAX_PRIORITY = 10
MIN_PRIORITY = 1
NORM_PRIORITY = 5
9. wait( ):-
This method is used to put in waiting until certain condition occurs.
Syn: t.wait( );
Thread Priority:
In java, each and every thread will be assigned with a priority. The priorities will effects the order of
execution of threads. The range of thread priority numbers is 1 to 10. The default priority is 5. There
are some pre – defined constant variables in thread class to represent priorities.
MAX_PRIORITY=10
MIN_PRIORITY=1
NORM_PRIORITY=5
We can set priority to a thread by using setPriority( ) method as shown below.
t.setPriority(number);
We can get the priority number of a thread by using getPriority( ) method as shown below.
int n = t.getPriority( );
When a thread is created, by default its priority is 5.
The processor spends more time on high priority thread.
The processor spends less time on low priority thread.
If multiple threads having the same priority, then the processor spends the time on a First
Come First Serve basis.
If multiple threads are ready for execution, then the processor chooses the highest priority
thread and executes it.
Thread Synchronization:
Preventing multiple threads acting on single object at a time is known as Thread Synchronization or
Thread safe. Thread synchronization is recommended, when the multiple threads are used to act on the
same object.
The object on the threads synchronization is called synchronized object. Synchronized object means
locked object on thread.
Booking(int i) {
wanted = i;
}
A thread is always in one of the above five states. It can move from one state to another state as shown
below.
2. Runnable state:
If the thread is ready for execution and is waiting for the availability of the processor then we
say that the thread is in runnable state.
3. Running state:
If a thread is in execution by the processor then we say that the thread is in running state.
In this state we can do the following things.
4. Blocked state:
If a thread execution is stopped temporarily by using wait( ) method or suspend( ) method or
sleep( ) method, then we say that the thread is in blocked state.
5. Dead state:
Every thread has a life cycle. A running thread ends it’s life, when it has completed execution
of it’s run( ) method. It is a natural death. We can also kill a thread by sending the stop
message at any state by using stop( ) method.