56 TANAY JAVA Exp14
56 TANAY JAVA Exp14
14
User Defined Exceptions
Name: Tanay More Date: 14/10
Roll No. 56 Batch G3
threads.
Theory:
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:
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:
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
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
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
PROGRAM/CODE:
class EvenOddPrinter {
private int limit;
private int number = 1;
private final Object lock = new Object();
// Create two threads: one for printing odd numbers, one for even numbers
Thread oddThread = new Thread(new Runnable() {
OUTPUT
Conclusion:
We used two threads, even and odd to print even , odd numbers simultaneously.