0% found this document useful (0 votes)
14 views

JAVA UNIT-4

JAVA UNIT-4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

JAVA UNIT-4

JAVA UNIT-4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

PA

JAVA PROGRAMMING GE
\*

UNIT-4(Chapter-1)
Multithreading

I. Java Language Classes (java.lang package)


The java.lang package contains the collection of base types (language types) that are always
imported into any given compilation unit. This is where you'll find the declarations of Object
(the root of the class hierarchy) and Class, plus threads, exceptions, wrappers for the primitive
data types, and a variety of other fundamental classes.

Note:The Boolean, Character, and Number classes--these classes are "wrapper" classes for the
primitive types. You use these classes in applications where the primitive types must be stored as
objects. Note also the Throwable class--this is the root class for all exceptions and errors.

Java provides built-in support for multithreaded programming. A multithreaded program


contains two or more parts that can run concurrently. Each part of such a program is called a
thread, and each thread defines a separate path of execution. Thus, multithreading is a
specialized form of multitasking

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Multiprogramming is a rudimentary form of parallel processing in which several programs are
run at the same time on a uni-processor. Since there is only one processor, there can be no true
simultaneous execution of different programs. Instead, the operating system executes part of one
program, then part of another, and so on. To the user it appears that all programs are executing at
the same time.

Multithreading:
● Multithreading in java is a process of executing multiple threads simultaneously.
● Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking. But we use
multithreading than multiprocessing because threads share a common memory area. They
don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
● Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

Multitasking:

● Multitasking, in an operating system, is allowing a user to perform more than one


computer task (such as the operation of an application program) at a time. The operating
system is able to keep track of where you are in these tasks and go from one to the other
without losing information
● Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved by two ways:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
1. Process-based Multitasking(Multiprocessing)
2. Thread-based Multitasking(Multithreading)

1. Process-based Multitasking (Multiprocessing)


● Each process has its own address in memory i.e. each process allocates separate
memory area.
● Process is heavyweight.

● Cost of communication between the processes is high.

● Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.

2. Thread-based Multitasking (Multithreading)


● Threads share the same address space.

● Thread is lightweight.

● Cost of communication between the thread is low.

Uses of Threads:

⮚ Threads are used to design server side programs to handle multiple clients at a time.
⮚ Threads are used in games and animations.
⮚ We can reduce the idle time of processor.
⮚ Performance of processor is improved.
⮚ Reduces interferences between execution and user interface.

Differences between multi-threading and multi-tasking:

MULTI THREADING MULTI TASKING


1)More than one thread running 1)More than one process running
Simultaneously simultaneously
2) It’s a part of program 2) It’s a program.
3) It is a light-weight process. 3) It is a heavy-weight process.
4) Threads are divided into sub threads 4) Process is divided into threads.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

5) Within the process threads are 5) Inter process communication is difficulty


Communicated.
6) Context switching between threads is 6) Context switching between process is
cheaper. costly
7) It is controlled by Java(JVM) 7) It is controlled by operating System.
8) It is a specialized form of multitasking 8) It is a generalized form of multithreading.
9) Example: java’s automatic garbage 8) Program compilation at command prompt
collector. window and preparing documentation at MS-
Office.

II. Life Cycle of a Thread


A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. The following diagram shows the complete life cycle of a thread.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

Following are the stages of the life cycle

1. New State:

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2. Runnable State (Ready State):

The thread is in runnable state after invocation of start() method, but the thread scheduler
has not selected it to be the running thread.

3. Running State:

The thread is in running state if the thread scheduler has selected it.

4. Non-Runnable (Blocked State):

This is the state when the thread is still alive, but is currently not eligible to run.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
5. Terminated State:

A thread is in terminated or dead state when its run() method exits.

III.The Main Thread

When a Java program starts up, one thread begins running immediately. This is usually called the
main thread of your program, because it is the one that is executed when your program begins.

The main thread is important for two reasons:

• It is the thread from which other “child” threads will be spawned.

• Often, it must be the last thread to finish execution because it performs various shutdown
actions.

Although the main thread is created automatically when your program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling the
method currentThread( ), which is a public static member of Thread.

This method returns a reference to the thread in which it is called. Once you have a reference to
the main thread, you can control it just like any other thread.

Program : Write a java program to know the currently running Thread

//Currently running thread

class Current

public static void main(String args[])

System.out.println ("This is first statement");

Thread t = Thread.currentThread ();

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
System.out.println ("Current Thread: " + t);

System.out.println ("Its name: " + t.getName ());

System.out.println ("Its priority:" + t.getPriority ());

IV.Creating Threads
We know that in every java program, there is a main thread available already. Apart from this
main thread, we can also create our own threads in a program. The following steps should be
used.

⮚ Write a class that extends “Thread” class or implements “Runnable” interface this is
available in lang package.
Class Myclass extends Thread

(or)

Class Myclass implements Runnable

⮚ Write public void run () method in that class. This is the method by default executed by
any thread.
public void run()

Statements;

⮚ Create an object to my class, so that the run() method is available for execution.
Myclassobj=new Myclass();

⮚ Create a thread and attach it to the object.


Thread t=new Thread(obj);

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
(or)

To create a Thread, we can use the following forms:

Thread t = new Thread (obj, "thread-name");

⮚ Start running the threads.


t.start();

Syntactical code for creating and running the thread:

Class Myclass extends Thread (or)


Class Myclass implements Runnable
{
public void run()
{
Statements;
}

}
Class Demo
{
public static void main(String args[])throws
InterruptedException
{
Myclassobj=new Myclass();
Thread t=new Thread(obj);
t.start();
}
}

Thread Class Methods:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
⮚ To know the currently running thread:
Thread t = Thread.currentThread ();
⮚ To start a thread:
t.start ();
⮚ To stop execution of a thread for a specific time:
Thread.sleep (milliseconds);
⮚ To get the name of the thread:
String name = t.getName ();
⮚ To set the new name to the thread:
t.setName ("New Name");
⮚ To get the priority of the thread:
int priority = t.getPriority();
⮚ To set the priority of the thread:
t.setPriority (int priority);
⮚ Thread priorities can change from 1 to 10. We can also use the following constants to
represent priorities:Thread.MAX_PRIORITY value is 10

Thread.MIN_PRIORITY value is 1

Thread.NORM_PRIORITY value is 5

⮚ To test if a thread is still alive:


t.isAlive () returns true/false
⮚ To wait till a thread dies:
t.join ();
⮚ To send a notification to a waiting thread:
obj.notify ();
⮚ To send notification to all waiting threads:
obj.notifyAll ();
⮚ To wait till the obj is released (till notification is sent):
obj.wait ();

Program : Write a program to create and run a Thread.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
//creating and running a Thread
classMyThread extends Thread
{
public void run ()
{
for (int i = 0;i<100;i++)
{
System.out.print (i + "\t");
}
}
}
Class TDemo
{ public static void main(String args[])
{ MyThread obj = new MyThread ();
Thread t = new Thread (obj);
t.start ();
}
}
As a result, the numbers will be displayed starting from 1 to 99 using a for loop. If u want to
terminate the program in the middle, u can press Ctrl+C from the keyboard. This leads to
abnormal program termination. It means the entire program is terminated, not just the thread.

If we want to terminate only the thread that is running the code inside run() method, we should
devise our own mechanism. if we press Ctrl+C, we are abnormally terminating the program. This
is dangerous. Abnormal program termination may cause loss of data and lead to unreliable
results. So, we should terminate the thread only, not the program. how can we terminate the
thread smoothly is the question now.

Terminating the thread:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
A thread will terminate automatically when it comes out of run() method. To terminate the thread
on our own logic
For the following steps can be used
1. Create the Boolean type variable and initialize it to false.
boolean stop=false;
2. Let us assume that we want to terminate the thread when the user presses <Enter> key.
So, when the user presses that button, make the Boolean type variable as true.
stop=true;
3. Check this variable in run() method and when it is true, make the thread return from the
run() method.
public void run()
{
if(stop==true) return;
}
Program to showing how to terminate the thread by pressing the enter button
import java.io.*;
class MyThread implements Runnable
{
boolean stop=false;
public void run ()
{
for (int i = 0;i<=100000;i++)
{
System.out.print (i + "\t");
if(stop==true) return; //come out of run
}
}
}
Class TDemo
Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE
PA
JAVA PROGRAMMING GE
\*
{
public static void main(String args[]) throws IOException
{
MyThread obj = new MyThread ();
Thread t = new Thread (obj);
t.start ();//stop the thread when enter key is pressed
System.in.read();
obj.stop=true;
}
}
Press <Enter> to stop the thread at any time.

What is the difference between ‘extends thread’ and ‘implements Runnable’ ? which one is
advantageous?
‘extends thread’ and ‘implements Runnable’-both are functionally same. But when we write
extends Thread, there is no scope to extend another class, as multiple inheritance is not supported
in java.

Class MyClass extends Thread,AnotherClass //invalid

If we write implements Runnable, then still there is scope to extend another class.

Class MyClass extends AnotherClass implements Runnable //valid

This is definitely advantageous when the programmer wants to use threads and also wants to
access the features of another class.

Single tasking using a thread:


A thread can be employed to execute one task at a time. Suppose there are 3 tasks to be executed.
We can create a thread and pass the 3 tasks one by one to the thread. For this purpose, we can
write all these tasks separately in separate methods; task1(), task2(), task3(). Then these methods
should be called from run() method, one by one. Remember, a thread executes only the code
inside the run() method. It can never execute other methods unless they are called from run().

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Note: public void run() method is executed by the thread by default.

//single tasking using a thread


classMyThread implements Runnable
{
public void run()
{
//executes tasks one by one by calling the methods.
task1();
task2();
task3();
}
void task1()
{
System.out.println("this is task1");
}
void task2()
{
System.out.println("this is task2");
}
void task3()
{
System.out.println("this is task3");
}
}
class Sin
{
public static void main(String args[])

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
{
MyThread obj=new MyThread();
Thread t1=new Thread(obj);
t1.start();
}
}

Multi-Tasking Using Threads:


In multi-tasking, several tasks are executed at a time. For this purpose, we need more than one
thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks.
Then those tasks are simultaneously executed by the two threads. Using more than one thread is
called ‘multi-threading’.

Program : Write a program to create more than one thread.


//using more than one thread is called Multi-Threading
class Theatre extends Thread
{
String str;
Theatre (String str)
{
this.str = str;
}
public void run()
{
for (int i = 1; i <= 10 ; i++)
{
System.out.println (str + " : " + i);
try
{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Thread.sleep (2000);
}
catch (InterruptedExceptionie)
{
ie.printStackTrace ();
}
}
}
}
class TDemo1
{
public static void main(String args[])
{
Theatre obj1 = new Theatre ("Cut Ticket");
Theatre obj2 = new Theatre ("Show Chair");
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t1.start ();
t2.start ();
}
}

Multiple Threads Acting on Single Object:


First let us see why 2 threads should share same object (same run()method). We write an object
to represent one task. If there is a different task, we take another object. When two people
(threads) want to perform same task then they need same object (run () method) to be
executed each time.

Example:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Railway reservation: Every day several people want reservation of a berth for them. The
procedure to reserve the berth is same for all the people. So we need some object with same run
() method to be executed repeatedly for all the people (threads).

Let us think that only one berth is available in a train and two passengers (threads) are asking for
that berth in two different counters. The clerks at different counters sent a request to the server to
allot that berth to their passengers. Let us see now to whom that berth is allotted.

Program: Write a program to create multiple threads and make the threads to action single
object.
//Thread unsafe –Two threads acting on same object.

class Reserve implements Runnable


{ //available berths are 1
int available = 1;
int wanted;
//accept wanted berths at runtime
Reserve (int i)
{
wanted = i;
}
public void run()
{//display available berths
System.out.println ("Number of berths available: " +
available);
//if available berths more than wanted betrhs
if ( available >= wanted)
{
//get the name of the passenger

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
String name = Thread.currentThread ().getName ();
System.out.println (wanted + " berths alloted to: " +
name);
try
{
Thread.sleep (2000); // wait for priniting the
ticket
available = available - wanted;
//update the no.of available berths
}
catch (InterruptedException ie)
{
ie.printStackTrace ();
}
}
else
{ System.out.println ("Sorry, no berth is available");
}
}
}
Class UnSafe
{
public static void main(String args[])
{
Reserve obj = new Reserve (1);
Thread t1 =new Thread (obj);
Thread t2 = new Thread (obj);
t1.setName ("First Person");

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
t2.setName ("Second Person");
t1.start ();
t2.start ();
}
}

Please observe the output in the preceding program. It is absurd. It has allotted the same berth to
both the passengers. Since both the threads are acting on the same object simultaneously, then
the result is unreliable.

Output:

What is the solution for this problem?


Ans: Thread Synchronization

V. Synchronizing Threads or Thread Synchronization or Thread Safe:

When a thread is acting on an object preventing other threads from acting on the same
object is called Thread Synchronization or Thread Safe. The object on which the threads are
synchronized is called ‘synchronized object’.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
The Object on which the Threads are synchronized is called synchronized object or
Mutex (Mutually Exclusive Lock).Synchronized object is like a locked object, locked on a
thread.

Example:

It is like a room with only one door. A person has entered the room and locked form it from
behind. The second person who wants to enter the room should wait till the first person comes
out.

In this way, a thread also locks the object after entering it. Then the next thread cannot enter it
till the first thread comes out. This means the object is locked mutually on threads. So, this object
is called ‘mutex’.

Thread synchronization is done in two ways:


⮚ Using synchronized block we can synchronize a block of statements.

synchronized (obj_lock)
{
statements;
}
Here, object represents the object to be locked or synchronized. The statements inside the
synchronized block are all available to only one thread at a time. They are not available to
more than one thread simultaneously.

⮚ To synchronize an entire method code we can use synchronized word before method
name
synchronized void method ()
{
Stmts;
}
Now the statements inside the method are not available to more than one thread at a time.
This method code is synchronized.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Write a program to thread synchronization by using synchronized block.
//Thread synchronization- Two threads acting on same object
//Multiple Threads acting on single object
class Reserve implements Runnable
{
int available = 1;
int wanted;
Reserve (int i)
{
wanted = i;
}
public void run()
{
synchronized (this)
{
System.out.println ("Number of berths available: " + available);
if ( available >= wanted)
{
String name = Thread.currentThread ().getName ();
System.out.println (wanted + " berths alloted to: " + name);
try
{
Thread.sleep (2000); // wait for priniting the ticket
available = available - wanted;
}
catch (InterruptedExceptionie)
{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
ie.printStackTrace ();
}
}
else
{
System.out.println ("Sorry, no berths available");
}
}
}
}
class Safe
{ public static void main(String args[])
{ Reserve obj = new Reserve (1);
Thread t1 =new Thread (obj,”Reyan”);
Thread t2 = new Thread (obj,”Ayan”);
t1.start ();
t2.start ();
}
}

Output:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

Write a program to thread synchronization by using synchronized keyword before the


method name
/** Write a Java program that creates three threads. First thread displays “Good
Morning” every one second, the second thread displays “Hello” every two seconds and the
third thread displays “Welcome” every threeseconds.*/
class A extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(1000);
System.out.println("good morning");
}
}
catch(Exception e)
{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
}
}
}
class B extends Thread
{
synchronized public void run()
{
try
{
while(true)
{
sleep(2000);
System.out.println("hello");
}
}
catch(Exception e)
{ }
}
}
class C extends Thread
{
synchronized public void run()
{
try
{
while(true)
{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
sleep(3000);
System.out.println("welcome");
}
}
catch(Exception e)
{ }
}
}
Class ThreadDemo
{
public static void main(String args[])
{
A t1=new A();
B t2=new B();
C t3=new C();
t1.start();
t2.start();
t3.start();
}
}

Output:
Press Cntrl+C to exit

VI.Thread Priority
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread scheduler schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which
scheduling it chooses.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int
NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10.

Example of priority of a Thread:


class Priority extends Thread
{
public void run()
{
System.out.println("running thread name is:"+Thread.currentThre
d().getName());
System.out.println("running thread priority is:"+Thread.currentT
hread().getPriority());

}
public static void main(String args[])
{
Priority m1=new Priority();
Priority m2=new Priority();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

VII. isAlive() and join()

Example: for isAlive():


class mythread extends Thread
{
public void run()
{
System.out.println("Thread Methods");

}
}
class mainforalive
{
public static void main(String ar[])
{
mythread obj=new mythread();
mythread obj1=new mythread();
obj.start();
System.out.println(obj.isAlive());

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
obj1.start();
System.out.println(obj1.isAlive());
}
}

Example:for without join():


class mythread extends Thread
{
public void run()
{
System.out.println("First calling of run() method");
try
{
Thread.sleep(3000);
}
catch(InterruptedException ie)
{
}
System.out.println("Second calling of run() method");
}
}
class withoutjoin
{
public static void main(String ar[])
{
mythread obj=new mythread();
mythread obj1=new mythread();

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
obj.start();
obj1.start();
}
}

Output:

Example: for join():


class mythread extends Thread

public void run()

System.out.println("First calling of run() method");

try

Thread.sleep(3000);

catch(InterruptedException ie)

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
System.out.println("Second calling of run() method");

class withjoin

public static void main(String ar[])

mythread obj=new mythread();

mythread obj1=new mythread();

obj.setName("Thread1");

obj1.setName("Thread2");

obj.start();

try

obj.join();

catch(InterruptedException ie)

obj1.start();

Output:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

VIII. Suspending and Resuming threads


When the sleep() method time is over, the thread becomes implicitly active. sleep() method is
preferable when the inactive time is known earlier. Sometimes, the inactive time or blocked time
may not be known to the programmer earlier; to come to the task here comes suspend() method.
The suspended thread will be in blocked state until resume() method is called on it. These
methods are deprecated, as when not used with precautions, the thread locks, if held, are kept in
inconsistent state or may lead to deadlocks.
Note: You must have noticed, in the earlier sleep() method, that the thread in blocked state
retains all its state. That is, attribute values remains unchanged by the time it comes into runnable
state.
The following program illustrates the usage of suspend() and resume() methods.

class SRDemo extends Thread


{
public void run()
{
try
{
for(int i = 0; i < 7; i++ )
{
Thread.sleep(1500);
System.out.println(this.getName() + ": " + i );
}

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
}
catch(InterruptedException e )
{

}
}
public static void main( String args[ ] )
{
SRDemo obj = new SRDemo();
SRDemo obj1 = new SRDemo();
obj.setName("First Thread");
obj1.setName("Second Thread");
obj.start();
obj1.start();
try
{
Thread.sleep( 1000 );
obj.suspend();
System.out.println(" First thread Suspending 1ms");
Thread.sleep( 1000 );
obj.resume();
System.out.println(" First thread Resuming");

Thread.sleep(2000);
obj1.suspend();
System.out.println("Second thread Suspending 2ms");
Thread.sleep(1000);
obj1.resume();
System.out.println("Second thread Resuming");
}
catch(InterruptedException e)
{
}
}
}

Output:
First thread Suspending 1ms
Second Thread:0
First thread Resuming
First Thread:0
Second Thread:1
First Thread:1
Second thread Suspending 2ms
Second Thread:2
Second thread Resuming
First Thread:2

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Second Thread:3
First Thread:3
Second Thread:4
First Thread:4
Second Thread:5
First Thread:5
Second Thread:6
First Thread:6

IX.Communication between Threads(Inter Process(or) Thread


Communication)
If you are aware of inter process communication then it will be easy for you to understand inter
thread communication. Inter thread communication is important when you develop an
application where two or more threads exchange some information.

There are simply three methods and a little trick which makes thread communication possible.
First let's see all the three methods listed below:

SN Methods with Description

public void wait()


1
Causes the current thread to wait until another thread invokes the notify().

public void notify()


2
Wakes up a single thread that is waiting on this object's monitor.

public void notifyAll()


3
Wakes up all the threads that called wait( ) on the same object.

These methods have been implemented as final methods in Object, so they are available in all
the classes. All three methods can be called only from within a synchronized context.
Example:

Here we are discussing an example which has two threads. One thread is printing even numbers
from 0 to 20, while the other thread is printing odd numbers from 0 to 20. Our aim is to print
even and odd numbers alternately.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

class even implements Runnable


{
int number = 2;
Object shared = null;
even(Object obj)
{
shared = obj;
}
public void run()
{
while (number < 20)
{
synchronized (shared)
{
System.out.println("Even number = " + number);
number = number + 2;
try
{
Thread.sleep(500); //only to view sequence of execution
shared.notify();
shared.wait();
}
catch (InterruptedException e)
{

}
}
}
}
}

class odd implements Runnable


{
int oddNumber = 1;
Object shared = null;
odd(Object obj)
{
shared = obj;
}
public void run()
{
while (oddNumber< 20)
{
synchronized (shared)
{
System.out.println("Odd number = " + oddNumber);

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
oddNumber = oddNumber + 2;
try
{
Thread.sleep(500); // only to view the sequence of execution
shared.notify();
shared.wait();
}
catch (InterruptedException e)
{

}
}
}
}
}

class ex
{

public static void main(String[] args)


{
Obj shared = new Object();
even obj = new even(shared);
odd obj1 = new odd(shared);
Thread evenThread = newThread(obj, "evenThread");
Thread oddThread = newThread(obj1, "oddThread");
oddThread.start();
evenThread.start();
}
}

Output:
Odd number = 1
Even number = 2
Odd number = 3
Even number = 4
Odd number = 5
Even number = 6
Odd number = 7
Even number = 8
Odd number = 9
Even number = 10
Odd number = 11
Even number = 12
Odd number = 13
Even number = 14
Odd number = 15

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Even number = 16
Odd number = 17
Even number = 18
Odd number = 19

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE

You might also like