Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Lecture9 Java

This document discusses multi-threading in Java. It defines a thread as a path of execution through a program. Multi-threading allows executing multiple tasks simultaneously using round-robin scheduling. Threads can be used in server programs to serve multiple clients concurrently and in games/animations. There are two ways to create threads: by extending the Thread class or implementing the Runnable interface. The document also discusses thread methods like start(), sleep(), getName(), setName(), and priorities. Thread synchronization prevents multiple threads from acting on a single object simultaneously.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lecture9 Java

This document discusses multi-threading in Java. It defines a thread as a path of execution through a program. Multi-threading allows executing multiple tasks simultaneously using round-robin scheduling. Threads can be used in server programs to serve multiple clients concurrently and in games/animations. There are two ways to create threads: by extending the Thread class or implementing the Runnable interface. The document also discusses thread methods like start(), sleep(), getName(), setName(), and priorities. Thread synchronization prevents multiple threads from acting on a single object simultaneously.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Advanced Programming 1

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.

1. By Using Thread Class:


We can create our own thread by defining sub class to the Thread class. This gives us access to all the
methods of Thread class directly. We have to follow the following steps to create our own thread.

Step 1: Define a class as a sub class to the Thread class as shown below.

Prepared by Krishna Kumari Ganga 1


Advanced Programming 1

Syn: class MyThread extends Thread {


-----
----
}

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 3: Create an object to the sub class as shown below.


Syn: MyThread mt = new MyThread( );

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;
}

public void run() {


for (int i = sp; i <= ep; i++) {
if ((i % 2) == 0) {
System.out.println("From Even: " + i);
}
}
}
}
class Odd extends Thread {
int sp, ep;

Odd(int a, int b) {
sp = a;
ep = b;
}

public void run() {


for (int i = sp; i <= ep; i++) {

Prepared by Krishna Kumari Ganga 2


Advanced Programming 1

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

2. By Using Runnable Interface:


We can also create a thread by implementing the Runnable interface. The Runnable interface declares
the run( ) method that is required for implementing threads in our program.
We have to follow the following steps to create a thread by using Runnable interface.

Step 1: Define a class as an implementation class to the Runnable interface.


Syn: class MyThread implements Runnable {
-----
----
}

Step 2: Implement the run( ) method and declare it as public with no return value(void).
Syn: class MyThread implements Runnable {
public void run( ) {

Prepared by Krishna Kumari Ganga 3


Advanced Programming 1

-----
----
}
}
In this run( ) method, we should write the code for the particular task executed by the thread.

Step 3: Create an object to the implementation class as shown below.


Syn: MyThread mt = new MyThread( );

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;
}

public void run() {


for (int i = sp; i <= ep; i++) {
if ((i % 2) == 0) {
System.out.println("From Even: " + i);
}
}
}
}
class Odd implements Runnable {
int sp, ep;

Odd(int a, int b) {
sp = a;
ep = b;
}

public void run() {


for (int i = sp; i <= ep; i++) {
if ((i % 2) != 0) {
System.out.println("From Odd: " + i);
}
}
}

Prepared by Krishna Kumari Ganga 4


Advanced Programming 1

}
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

Thread Class Methods:


1. currentThread( ):-
This method is used to know the currently running thread.
Syn: Thread t = Thread.currentThread( );

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();

Prepared by Krishna Kumari Ganga 5


Advanced Programming 1

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( );

10. notify( ):-


This method is used to send notification to a waiting thread.
Syn: t.notify( );

11. notifyAll( ):-


This method is used to send notification to all waiting threads.
Syn: t.notifyAll( );

12. stop( ):-


This method is used to stop a thread.
Syn: t.stop( );

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.

Prepared by Krishna Kumari Ganga 6


Advanced Programming 1

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.

There are two ways to synchronize an object.


1. By using synchronized block
2. By using synchronized keyword

1. By using synchronized block:


We can synchronize a group of statements to the thread by using synchronized block as shown
below.
Syn: synchronized(this) {
……………
Statements;
……………
}
The statements with in synchronized block are available only one thread at a time. They are not
available for more than one thread simultaneously.

2. By using synchronized keyword:


We can also synchronize an entire method by using synchronized keyword. If we want to
synchronize the code of a method, then place the synchronized keyword before the method name
as shown below.
synchronized public void run( ) {
……………
Statements;
……………
}
The statements with in synchronized method are available only one thread at a time. They are not
available more than one thread simultaneously.
Ex:
class Booking implements Runnable {
int available = 1, wanted;

Prepared by Krishna Kumari Ganga 7


Advanced Programming 1

Booking(int i) {
wanted = i;
}

synchronized public void run() {


Thread t = Thread.currentThread();
String name = t.getName();
try {
if (available < wanted) {
System.out.println(" Tickets are not available for " + name);
} else {
System.out.println(wanted + " Tickets are booked for " + name);
t.sleep(1000);
available = available - wanted;
}
} catch (Exception e) {
}
}
}
class TicketBook {
public static void main(String args[]) {
Booking b1 = new Booking(1);
Thread t1 = new Thread(b1);
Thread t2 = new Thread(b1);
t1.setName("Fathima");
t2.setName("Mohammed");
t1.start();
t2.start();
}
}
Output:
1 Tickets are booked for Fathima
Tickets are not available for Mohammed

Life cycle of a Thread:


During the lifetime of a thread, a thread enters in to many states. There are five states in threads life
cycle.
They are listed below.
1. New born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

A thread is always in one of the above five states. It can move from one state to another state as shown
below.

Prepared by Krishna Kumari Ganga 8


Advanced Programming 1

1. New born state:


When we create a thread, then we say that thread is born. This state is known as new born
state. In the new born state the thread is not scheduled for running. In this state we can do only
one of the following things.
a. Scheduling it for running by using start( ) method.
b. Kill it by using stop( ).

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.

Q. What is Daemon Thread?


ANS: A thread which is providing the services continuously is called as daemon thread. It starts the
services when the system started up.

Prepared by Krishna Kumari Ganga 9

You might also like