Multithreading Java
Multithreading Java
1
Java Thread Methods
2
12) static void yield() It causes the currently executing
thread object to pause and allow
other threads to execute
temporarily.
3
error stream.
4
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states.
A thread lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
5
3. Blocked: The thread will be in blocked state when it is trying to acquire a
lock but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait()
method or join() method. It will move to the runnable state when other
thread will notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a
method with a time-out parameter. A thread lies in this state until the
timeout is completed or until a notification is received. For example, when
a thread calls sleep or a conditional wait, it is moved to a timed waiting
state.
6. Terminated State: A thread terminates because of either of the
following reasons:
Because it exits normally. This happens when the code of the thread
has been entirely executed by the program.
Because there occurred some unusual erroneous event, like a
segmentation fault or an unhandled exception.
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.
6
Java Thread Example by extending Thread class
FileName: Multi.java
7
2) Java Thread Example by implementing 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().
If you are not extending the Thread class, your class object would
not be treated as a thread object. So you need to explicitly create
the Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.
Starting a thread:
The start() method of Thread class is used to start a newly created thread.
It performs the following tasks:
Output:
thread is running...
8
Java Multiple Threads Example by implementing Runnable
interface
We can directly use the Thread class to spawn new threads using the constructors
defined above.
public class MyThread1
1. {
2. // Main method
3. public static void main(String argvs[])
4. {
5. // creating an object of the Thread class using the constructor Thread(String
name)
6. Thread t= new Thread("My first thread");
7.
8. // the start() method moves the thread to the active state
9
9. t.start();
10. // getting the thread name by invoking the getName() method
11. String str = t.getName();
12. System.out.println(str);
13. }
14. }
FileName: MyThread2.java
10
24. }
Output:
My new thread
Now the thread is running ...
Time of Arrival: Suppose two threads of the same priority enter the
runnable state, then priority cannot be the factor to pick a thread from these
two threads. In such a case, arrival time of thread is considered by the
thread scheduler. A thread that arrived first gets the preference over the
other threads.
12
The Thread.sleep() method can be used with any thread. It means any other thread
or the main thread can invoke the sleep() method.
Parameters:
The following are the parameters used in the sleep() method.
If the system that is executing the threads is busy, then the actual sleeping
time of the thread is generally more as compared to the time passed in
arguments. However, if the system executing the sleep() method has less
load, then the actual sleeping time of the thread is almost equal to the time
passed in the argument.
FileName: TestSleepMethod1.java
13
13. t1.start();
14. t2.start();
15. }
16. }
Example
14
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "+ t1.getPriority());
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "+ t3.getPriority());
// Setting priorities of above threads by
// passing integer arguments
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
15
When a Java program starts up, one thread begins running immediately. This
is usually called the main thread of our program because it is the one that is
executed when our program begins.
There are certain properties associated with the main thread which are as
follows:
It is the thread from which other “child” threads will be spawned.
Often, it must be the last thread to finish execution because it performs
various shutdown actions
The flow diagram is as follows:
Example
16
// Java program to control the Main Thread Importing required classes
import java.io.*;
import java.util.*;
// Class 1 Main class extending thread class
public class Test extends Thread {
// Main driver method
public static void main(String[] args)
{
// Getting reference to Main thread
Thread t = Thread.currentThread();
// Getting name of Main thread
System.out.println("Current thread: "+ t.getName());
// Changing the name of Main thread
t.setName("Geeks");
System.out.println("After name change: " + t.getName());
// Getting priority of Main thread
System.out.println("Main thread priority: "+ t.getPriority());
// Setting priority of Main thread to MAX(10)
t.setPriority(MAX_PRIORITY);
// Print and display the main thread priority
System.out.println("Main thread new priority: "+ t.getPriority());
for (int i = 0; i < 5; i++) {
System.out.println("Main thread");
}
// Main thread creating a child thread
Thread ct = new Thread() {
// run() method of a thread
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Child thread");
}
}
};
17
// Class 2
// Helper class extending Thread class
// Child Thread class
class ChildThread extends Thread {
@Override public void run()
{
for (int i = 0; i < 5; i++) {
Let us see what happens if we don’t call start() and rather call run()
directly. We have modified the first
// Java code to see that all threads are pushed on same stack if we use run()
instead of start().
class ThreadTest extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +Thread.currentThread().getId() +" is
running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
18
}
}
// Main Class
public class Main
{
public static void main(String[] args)
{
int n = 8;
for (int i=0; i<n; i++)
{
ThreadTest object = new ThreadTest();
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Now, let us try to call run() method directly instead of start() method:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());
class GeeksforGeeks {
public static void main(String[] args)
19
{
MyThread t = new MyThread();
t.run();
}
}
Output:
Current thread name: main
run() method called
start() run()
Creates a new thread and the run() No new thread is created and the
method is executed on the newly run() method is executed on the
created thread. calling thread itself.
Defined
in java.lang.Runnable interface
Defined in java.lang.Thread class.
and must be overridden in the
implementing class.
20
1. join(): It will put the current thread on wait until the thread on which it is called is
dead. If thread is interrupted then it will throw InterruptedException.
Syntax:
2. public final void join()
3. join(long millis) :It will put the current thread on wait until the thread on which it
is called is dead or wait for specified time (milliseconds).
Syntax:
4. public final synchronized void join(long millis)
5. join(long millis, int nanos): It will put the current thread on wait until the
thread on which it is called is dead or wait for specified time (milliseconds
+ nanos).
Syntax:
public final synchronized void join(long millis, int
nanos)
catch(Exception ex)
{
System.out.println("Exception has" +
" been caught" + ex);
}
System.out.println(i);
}
21
}
}
class GFG
{
public static void main (String[] args)
{
// thread t1 starts
t1.start();
catch(Exception ex)
{
System.out.println("Exception has " +
"been caught" + ex);
}
// t2 starts
t2.start();
catch(Exception ex)
{
System.out.println("Exception has been" +
" caught" + ex);
22
}
t3.start();
}
}
output:
Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-2
0
Current Thread: Thread-2
1
There are many java daemon threads running automatically e.g. gc, finalizer
etc.
23
Why JVM terminates the daemon thread if there is no user
thread?
The sole purpose of the daemon thread is that it provides services to user
thread for background supporting task. If there is no user thread, why should
JVM keep running this thread. That is why JVM terminates the daemon thread
if there is no user thread.
24
16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. }
21. }
Output:
Note: If you want to make a user thread as Daemon, it must not be started otherwise
it will throw IllegalThreadStateException.
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.
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.
25
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:
26
17. } }
18. class MyThread2 extends Thread{
19. Table t;
20. MyThread2(Table t){
21. this.t=t;
22. }
23. public void run(){
24. t.printTable(100);
25. } }
26. class TestSynchronization1{
27. public static void main(String args[]){
28. Table obj = new Table();//only one object
29. MyThread1 t1=new MyThread1(obj);
30. MyThread2 t2=new MyThread2(obj);
31. t1.start();
32. t2.start();
33. } }
Output:
5
100
10
200
15
300
20
400
25
500
1. class Table{
27
2. synchronized 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){System.out.println(e);}
8. } } }
9.
10. class MyThread1 extends Thread{
11. Table t;
12. MyThread1(Table t){
13. this.t=t;
14. }
15. public void run(){
16. t.printTable(5);
17. } }
18. class MyThread2 extends Thread{
19. Table t;
20. MyThread2(Table t){
21. this.t=t;
22. }
23. public void run(){
24. t.printTable(100);
25. } }
26. class TestSynchronization1{
27. public static void main(String args[]){
28. Table obj = new Table();//only one object
29. MyThread1 t1=new MyThread1(obj);
30. MyThread2 t2=new MyThread2(obj);
31. t1.start();
32. t2.start();
33. } }
Output:
5
10
15
20
28
25
100
200
300
400
500
If we put all the codes of the method in the synchronized block, it will work
same as the synchronized method.
Points to Remember
Syntax
1. class Table
2. {
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){
29
6. System.out.println(n*i);
7. try{
8. Thread.sleep(400);
9. }catch(Exception e){System.out.println(e);}
10. } } }//end of the method }
11.
12. class MyThread1 extends Thread{
13. Table t;
14. MyThread1(Table t){
15. this.t=t;
16. }
17. public void run(){
18. t.printTable(5);
19. } }
20. class MyThread2 extends Thread{
21. Table t;
22. MyThread2(Table t){
23. this.t=t;
24. }
25. public void run(){
26. t.printTable(100);
27. } }
28.
29. public class TestSynchronizedBlock1{
30. public static void main(String args[]){
31. Table obj = new Table();//only one object
32. MyThread1 t1=new MyThread1(obj);
33. MyThread2 t2=new MyThread2(obj);
34. t1.start();
35. t2.start();
36. } }
Output:
37. 5
38. 10
39. 15
40. 20
41. 25
42. 100
43. 200
30
44. 300
45. 400
46. 500
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
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
31
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.
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...");
}
//Threads Thread 1
public class ThreadforWithdrawl extends Thread {
Customer c;
int amount;
32
c.withdraw(amount);
}
}
//Thread thread 2
public class ThreadforDeposit extends Thread{
Customer c;
int amount;
// test Class
public class Test {
thrwithdraw.start();
thrdeposit.start();
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed...
33