Threads and Thread synchronization in java
Threads and Thread synchronization in java
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
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.
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.
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().
Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. 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:
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 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.
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
Output:
5
10
15
20
25
100
200
300
400
500
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of
the given thread.
package p1;
// 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());
// 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
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;
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.)
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(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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
Syntax:
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.
wait() sleep()
The wait() method releases the lock. The sleep() method doesn't release the lock.
Test.java
package p1;
class Customer{
int amount=10000;
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...");
}
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