Multithreading in Java
Multithreading in java is a process of
executing multiple threads simultaneously.
Thread is basically a lightweight
sub-process, a smallest unit of processing. Multiprocessing and multithreading,
both are used to achieve multitasking.
But we use multithreading than
multiprocessing because threads share a common memory area. They don't allocate
separate memory area so saves memory, and context-switching between the threads
takes less time than process.
Java Multithreading is mostly used in
games, animation etc.
Advantage of Java Multithreading
1) It doesn't block the user
because threads are independent and you can perform multiple operations at same
time.
2) You can perform many operations
together so it saves time.
3) Threads are independent so it
doesn't affect other threads if exception occur in a single thread.
As shown in the above figure, thread is
executed inside the process. There is context-switching between the threads.
There can be multiple processes inside the OS and one process can have multiple
threads.
Life cycle
of a Thread (Thread States)
1. New
2. Runnable
3. Running
5. Terminated
A thread can be in one of the five
states. According to sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated. There is no running
state.
But for better understanding the
threads, we are explaining it in the 5 states.
The life cycle of
the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable
(Blocked)
5. Terminated
1)New
The thread is in new state if you
create an instance of Thread class but before the invocation of start()
method.
|
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has
selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run()
method exits.
How to
create thread
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:
·
Thread()
·
Thread(String name)
·
Thread(Runnable r)
·
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.
|
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:
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. This can be done by
three ways in java:
1. by synchronized
method
2. by synchronized block
3. by static
synchronization
Concept of Lock in Java
Synchronization is built around an
internal entity known as the lock or monitor. Every object has an 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:
Class Table{
void printTable(int n){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
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.
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
Synchronized
block in java
Synchronized block can be used to
perform synchronization on any specific resource of the method.
Suppose you have 50 lines of code in
your method, but you want to synchronize only 5 lines, you can use
synchronized block.
If you put all the codes of the
method in the synchronized block, it will work same as the synchronized
method.
Points to remember
for Synchronized block
·
Synchronized block is used to lock an object for any
shared resource.
·
Scope of synchronized block is smaller than the method.
Syntax to use
synchronized block
synchronized (object reference expression) {
//code block
}
class Table{
void printTable(int n){
synchronized(this){
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronizedBlock1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
Output:5
10
15
20
25
100
200
300
400
500
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:
·
wait()
·
notify()
·
notifyAll()
1) 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.
2) 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()
wait(), notify() and notifyAll() methods
are defined in Object class not in Thread class.
Difference between wait and sleep
Example of inter thread
communication in java
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
|
0 Comments