0% found this document useful (0 votes)
24 views11 pages

56 TANAY JAVA Exp14

Ggdd

Uploaded by

Deadly Ninja
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)
24 views11 pages

56 TANAY JAVA Exp14

Ggdd

Uploaded by

Deadly Ninja
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/ 11

Experiment No.

14
User Defined Exceptions
Name: Tanay More Date: 14/10
Roll No. 56 Batch G3

Aim: WAP to print even and odd no using two

threads.

Theory:

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.
In a thread-based multitasking environment, the thread is the smallest unit of
dispatch able code. This means that a single program can perform two or more
tasks simultaneously. For instance, a text editor can format text at the same
time that it is printing, as long as these two actions are being performed by two
separate threads.
Thus, process-based multitasking deals with the “big picture,” and thread-based
multitasking handles the details.
Creating a Thread

In the most general sense, you create a thread by instantiating an object of type
Thread. Java defines two ways in which this can be accomplished:

■ You can implement the Runnable interface.


■ You can extend the Thread class, itself.

The following two sections look at each method, in turn.

Implementing Runnable

The easiest way to create a thread is to create a class that implements the
Runnable interface. Runnable abstracts a unit of executable code. You can
construct a thread on any object that implements Runnable. To implement
Runnable, a class need only implement a single method called run ( ), which is
declared like this:

public void run( )

SIES GRADUATE SCHOOL OF Page 1


TECHNOLOGY
Inside run( ), you will define the code that constitutes the new thread.

Extending Thread

The second way to create a thread is to create a new class that extends Thread,
and then to create an instance of that class. The extending class must override the
run( ) method, which is the entry point for the new thread. It must also call
start( ) to begin execution of the new thread. Here is the

preceding program
rewritten to

class NewThread extends Thread

// Create a second thread by


extending Thread class
NewThread extends Thread {
NewThread() {
// Create a new,
second thread
super("Demo Thread");
System.out.println("Child
thread: " + this); start(); //
Start the thread
}
// This is the entry point for the second thread.
public void main()
{
try
{
for(int i = 5; i >
0; i--

System.out.println("Child
Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
This program generates the same output as the preceding version. As you can
see, the child thread is created by instantiating an object of NewThread, which

SIES GRADUATE SCHOOL OF Page 2


TECHNOLOGY
is derived from Thread.

Notice the call to super( ) inside NewThread. This invokes the following form of the
Thread
constructor:
public
Thread(String threadName) Here,
threadName specifies the name of the
thread.
Thread Synchronization
To enter an object’s monitor, just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized method, all
other threads that try to call it (or any other synchronized method)
on the same instance have to wait.

When two or more threads need access to a shared resource, they need some
way to ensure that the resource will be used by only one thread at a time. The
process by which this is achieved is called synchronization.
class Callme {
synchronized void call(String msg) {
...
}
This prevents other threads from entering call( ) while another thread is using it.
Two ways exist to determine whether a thread has finished. First, you can call
isAlive( ) on the thread. This method is defined by Thread, and its general form
is shown here:
final boolean isAlive( )
The isAlive( ) method returns true if the thread upon which it is called is still running. It
returns
false otherwise.
While isAlive( ) is occasionally useful, the method that you will more commonly use
to wait for a thread to finish is called join( ), shown here:
final void join( ) throws InterruptedException

SIES GRADUATE SCHOOL OF Page 3


TECHNOLOGY
This method waits until the thread on which it is called terminates. Its name
comes from the concept of the calling thread waiting until the specified thread
joins it. Additional forms of join( ) allow you to specify a maximum amount of
time that you want to wait for the specified thread to terminate.
Here is an improved version of the preceding example that uses join( ) to ensure
that the main thread is the last to stop. It also demonstrates the isAlive( )
method.
class DemoJoin {
public static void
main(String args[]) { NewThread ob1
= new NewThread("One");
NewThread ob2 = new
NewThread("Two"); NewThread ob3
= new NewThread("Three");
System.out.println("Thread One is
alive: "
+ ob1.t.isAlive());
System.out.println("Threa
d Two is alive: "
+ ob2.t.isAlive());
System.out.println("Thread
Three is alive: "
+ ob3.t.isAlive());
// wait for
threads to
finish try {
System.out.println("Waiting for threads to
finish."); ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread
Interrupted");
}
after the calls to join( ) return, the threads have stopped executing.

PROGRAM/CODE:

// Paste code block here.

class EvenOddPrinter {
private int limit;
private int number = 1;
private final Object lock = new Object();

public EvenOddPrinter(int limit) {


SIES GRADUATE SCHOOL OF Page 4
TECHNOLOGY
this.limit = limit;
}

// Method to print odd numbers


public void printOdd() {
synchronized (lock) {
while (number <= limit) {
if (number % 2 == 0) {
try {
lock.wait(); // Wait for even thread
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
System.out.println("Odd: " + number);
number++;
lock.notify(); // Notify the even thread
}
}
}
}

// Method to print even numbers


public void printEven() {
synchronized (lock) {
while (number <= limit) {
if (number % 2 != 0) {
try {
lock.wait(); // Wait for odd thread
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} else {
System.out.println("Even: " + number);
number++;
lock.notify(); // Notify the odd thread
}
}
}
}
}

// Main class to run the program


public class EvenOddThread {
public static void main(String[] args) {
int limit = 10; // Change the limit as per your requirement
EvenOddPrinter printer = new EvenOddPrinter(limit);

// Create two threads: one for printing odd numbers, one for even numbers
Thread oddThread = new Thread(new Runnable() {

SIES GRADUATE SCHOOL OF Page 5


TECHNOLOGY
@Override
public void run() {
printer.printOdd();
}
});

Thread evenThread = new Thread(new Runnable() {


@Override
public void run() {
printer.printEven();
}
});

// Start both threads


oddThread.start();
evenThread.start();
}
}

OUTPUT

Conclusion:
We used two threads, even and odd to print even , odd numbers simultaneously.

SIES GRADUATE SCHOOL OF Page 6


TECHNOLOGY
SIES GRADUATE SCHOOL OF Page 7
TECHNOLOGY
SIES GRADUATE SCHOOL OF Page 8
TECHNOLOGY
SIES GRADUATE SCHOOL OF Page 9
TECHNOLOGY
SIES GRADUATE SCHOOL OF Page 10
TECHNOLOGY
SIES GRADUATE SCHOOL OF Page 11
TECHNOLOGY

You might also like