0% found this document useful (0 votes)
25 views16 pages

Threads and Thread synchronization in java

Uploaded by

ARYAN Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
25 views16 pages

Threads and Thread synchronization in java

Uploaded by

ARYAN Shukla
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 16

What is Thread in java

A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of


execution.

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the new
state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active
state. The active state contains two states within it: one is runnable, and the other
is running.

• Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given
instant of time. It is the duty of the thread scheduler to provide the thread time to
run, i.e., moving the thread the running state.

• Running: When the thread gets the CPU, it moves from the runnable to the
running state. Generally, the most common change in the state of a thread is
from runnable to running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name
is A) has entered the critical section of a code and is not willing to leave that critical section.
In such a scenario, another thread (its name is B) has to wait forever, which leads to
starvation.

Terminated: A thread reaches the termination state because of the following reasons:
o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface

Thread class:
Thread class provide constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r, String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread. JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to
sleep (temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing
thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.

Java Thread Example by extending Thread class

package p1;
// Thread is a class having two methods run() and start()
public class A extends Thread{
@Override
public void run() {
for(int i=0;i<10000;i++) {
System.out.println("run");
}
}
public static void main(String[] args) {
A a1=new A();
a1.start();// start() is used for calling of run()
for(int i=0;i<10000;i++) {
System.out.println("main");
}
}
}

Output
run run
run run
run main
main run

Note:In above program we have created two threads namely “run” and
“main”. Above output may be or might be changes each and every time
while we execute the threads.
package p2;
public class A extends Thread {
String name;
A(String name){
this.name=name;
}
@Override
public void run() {
for(int i=0;i<10000;i++) {
System.out.println(this.name);
}
}
}

package p2;
public class B {
public static void main(String[] args) {
A a1=new A("xxx");
A a2=new A("yyy");
A a3=new A("zzz");
a1.start();
a2.start();
a3.start();
}
}
Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().

1. public void run(): is used to perform action for a thread.

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

Java Thread Example by implementing Runnable interface


package p3;

public class A implements Runnable{


String name;
A(String name){
this.name=name;
}
@Override
public void run() {
for(int i=0;i<10000;i++) {
System.out.println(this.name);
}
}
public static void main(String[] args) {
A a1=new A("xxx");
Thread t1=new Thread(a1);
t1.start();
A a2=new A("yyy");
Thread t2=new Thread(a2);
t2.start();
for(int i=0;i<10000;i++) {
System.out.println("main");
}
}
}
Threads Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. 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:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. 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.

Understanding the problem without Synchronization


In this example, there is no synchronization, so output is inconsistent. Let's see the
example:

TestSynchronization1.java

1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){
8. System.out.println(e);}
9. }
10.
11. }
12. }

1. class MyThread1 extends Thread{


2. Table t;
3. MyThread1(Table t){
4. this.t=t;
5. }
6. public void run(){
7. t.printTable(5);
8. }
9. }

1. class MyThread2 extends Thread{


2. Table t;
3. MyThread2(Table t){
4. this.t=t;
5. }
6. public void run(){
7. t.printTable(100);
8. }
9. }

1. class TestSynchronization1{
2. public static void main(String args[]){
3. Table obj = new Table();//only one object
4. MyThread1 t1=new MyThread1(obj);
5. MyThread2 t2=new MyThread2(obj);
6. t1.start();
7. t2.start();
8. }
9. }

Output:

5
100
10
200
15
300
20
400
25
500
Java Synchronized Method
If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

TestSynchronization2.java

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }

1. class MyThread1 extends Thread{


2. Table t;
3. MyThread1(Table t){
4. this.t=t;
5. }
6. public void run(){
7. t.printTable(5);
8. }
9.
10. }

1. class MyThread2 extends Thread{


2. Table t;
3. MyThread2(Table t){
4. this.t=t;
5. }
6. public void run(){
7. t.printTable(100);
8. }
9. }

1. public class TestSynchronization2{


2. public static void main(String args[]){
3. Table obj = new Table();//only one object
4. MyThread1 t1=new MyThread1(obj);
5. MyThread2 t2=new MyThread2(obj);
6. t1.start();
7. t2.start();
8. }
9. }

Output:

5
10
15
20
25
100
200
300
400
500

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10. In most
cases, the 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. Note that not only JVM a Java programmer can also assign the
priorities of a thread explicitly in a Java program.
Setter & Getter Method of Thread Priority
Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of
the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method


updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1 (minimum)
to 10 (maximum).

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:


FileName: ThreadPriorityExample.java

package p1;

public class ThreadPriorityExample extends Thread {


// Importing the required classes
// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}
// the main method
public static void main(String args[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();

// We did not mention the priority of the thread.


// Therefore, the priorities of the thread is 5, the default value

// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// Setting priorities of above threads by


// passing integer arguments
th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);

// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());

// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());

// Main thread

// Displaying name of the currently executing thread


System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());

System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

// Priority of the main thread is 10 now


Thread.currentThread().setPriority(10);

System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());


}
}
Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

We know that a thread with high priority will get preference over lower priority threads when it comes
to the execution of threads. However, there can be other scenarios where two threads can have the
same priority. All of the processing, in order to look after the threads, is done by the Java thread
scheduler. Refer to the following example to comprehend what will happen if two threads have the
same priority.

FileName: ThreadPriorityExample1.java

package p1;

public class ThreadPriorityExample1 extends Thread {


// Method 1
// Whenever the start() method is called by a thread
// the run() method is invoked
public void run()
{
// the print statement
System.out.println("Inside the run() method");
}

// the main method


public static void main(String argvs[])
{

// Now, priority of the main thread is set to 7


Thread.currentThread().setPriority(7);

// the current thread is retrieved


// using the currentThread() method

// displaying the main thread priority


// using the getPriority() method of the Thread class
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());

// creating a thread by creating an object of the class ThreadPriorityExample1


ThreadPriorityExample1 th1 = new ThreadPriorityExample1();

// th1 thread is the child of the main thread


// therefore, the th1 thread also gets the priority 7
// Displaying the priority of the current thread
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
}
}

Output:
Priority of the main thread is : 7
Priority of the thread th1 is : 7

Explanation: If there are two threads that have the same priority, then one can not predict which
thread will get the chance to execute first. The execution then is dependent on the thread scheduler's
algorithm (First Come First Serve, Round-Robin, etc.)

Inter-thread Communication in Java


Inter-thread communication or Co-operation is all about allowing synchronized
threads to communicate 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:

o wait()
o notify()
o 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()throws InterruptedException It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of time.
InterruptedException
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()

Note: Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?
Ans. It is because they are related to lock and object has a lock.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or After the specified amount of time, sleep is


notifyAll() methods completed.

Example of Inter Thread Communication in Java


Let's see the simple example of inter thread communication.

Test.java

package p1;
class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}
}

Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

You might also like