Java 4 TH
Java 4 TH
Java 4 TH
3) static void sleep() It sleeps a thread for the specified amount of time.
4) static Thread currentThread() It returns a reference to the currently executing thread
object.
CRETING MULTI-THREAD
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the run() method available in
the Thread class. A thread begins its life inside run() method. We create an object of our new class and call
start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Example:
class MultithreadingDemo extends Thread {
public void run()
{
try {
System.out.println(
"Thread " + Thread.currentThread().getId() + " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Thread creation by implementing runnable interface:
The Runnable interface describes a class whose instances can be run as a thread. The interface itself is very
simple, describing only one method (run) that is called automatically by Java when the thread is started.
Example:
class MultithreadingDemo implements Runnable {
public void run()
{
try {
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
}
catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
THREAD PRIARITIES IN MULTIPLE THREADS
Every java thread has a priority that helps the operating system determine the order in which threads are
scheduled. Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads.
Java Thread Priority in Multithreading
MAX_PRIORITY − The maximum priority that a thread has, whose default value is 10.
NORM_PRIORITY − The default priority that a thread has, whose default value is 5.
MIN_PRIORITY − The minimum priority that a thread has, whose default value is 1.
Use of isAlive() and join() methods in thread priority.
isAlive(): The isAlive function − It is used to check if a thread is alive or not. Alive refers to a thread
that has begun but not been terminated yet. When the run method is called, the thread operates for a
specific period of time after which it stops executing.
Syntax: final Boolean isAlive()
join(): Join method in Java allows one thread to wait until another thread completes its execution. In
simpler words, it means it waits for the other thread to die. It has a void type and throws
InterruptedException.
Syntax: public final void join() throws InterruptedException
Example:
import java.lang.*;
public class Demo implements Runnable {
public void run() {
Thread t = Thread.currentThread(); // tests if this thread is alive
System.out.println("thread is live = " + t.isAlive()); // tests if this thread is alive
}
public static void main(String args[]) throws Exception {
Thread t = new Thread(new Demo());
t.start(); // this will call run() function
t.join(); // waits for this thread to die
System.out.println("thread is live = " + t.isAlive()); // tests if this thread is alive
}
}
Output:
thread is live = true
thread is live = false
CONCEPT OF SYNCHRONIZATION
The synchronization is a capability to control the access of multiple threads to any shared resource. The
process by which this synchronization is called thread synchronization. Every java object with a critical section
of code gets a lock associated with the object.
Syntax:
synchronized (object)
{
//statement to be sychronized
}
The synchronization is mainly used to
To prevent thread interference.
To prevent consistency problem.
Types of Synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
1. Mutual Exclusive
Synchronized method.
Synchronized block.
Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It can be achieved
by using the following three ways:
By Using Synchronized Method
By Using Synchronized Block
By Using Static Synchronization
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or monitor. Every object has a lock
associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them. From Java 5 the
package java.util.concurrent.locks contains several lock implementations.
Synchronized block in java
A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource
of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a
synchronized block is smaller than the synchronized method.
Problem with using synchronization
The JVM uses the object itself as a monitor when a class implements method synchronization or block
synchronization with the This keyword. Untrusted code can obtain and indefinitely hold the inbuilt lock of an
accessible class. Consequently, this can result in a deadlock situation.
Example:
synchronized void updatesum (int i)
{
Thread t = Thread.currentThread();
for(int n=1; n<=5; n++)
{
System.out.println(t.getName()+ “;”+(i+n));
Table obj=new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
} }
INTER THREAD COMMUNICATION
Inter-thread communication or co-operation is all about allowing synchronized threads are to be
communicated with each other. Cooperation (Inter-thread communication) is a mechanism in which a thread
is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical
section to be executed. It is implemented by following methods of Object class.
wait()
notify()
notifyAll()
1) wait() method
The wait() method causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The
current thread must own this object's monitor, so it must be called from the synchronized method only
otherwise it will throw exception.
Method Description
public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time
2) notify() method
The notify() method wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of
the implementation.
Syntax: public final void notify()
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax: public final void notifyAll()
Understanding the process of inter-thread communication
Example:
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
Thread t2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}