MULTITHREADING
Java is a multi-threaded programming language which
means we can develop multi-threaded program using
Java. A multi-threaded program contains two or more
parts that can run concurrently and each part can handle
a different task at the same time making.
By definition, multitasking is when multiple processes
share common processing resources such as a CPU. Multi-
threading extends the idea of multitasking into
applications where you can subdivide specific operations
within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing
time not only among different applications, but also
among each thread within an application.
Life Cycle of a Thread in Java Multithreading
A thread goes through various stages in its life cycle. For
example, a thread is born, started, runs, and then dies.
The following diagram shows the complete life cycle of a
thread.
Following are the stages of the life cycle –
New − A new thread begins its life cycle in the new state.
It remains in this state until the program starts the
thread. It is also referred to as a born thread. New()
Runnable − After a newly born thread is started, the
thread becomes runnable. A thread in this state is
considered to be executing its task. Start()
Waiting − Sometimes, a thread transitions to the waiting
state while the thread waits for another thread to perform
a task. A thread transitions back to the runnable state
only when another thread signals the waiting thread to
continue executing.
Timed Waiting − A runnable thread can enter the timed
waiting state for a specified interval of time. A thread in
this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for
occurs.
Terminated (Dead) − A runnable thread enters the
terminated state when it completes its task or otherwise
terminates.
First Come First Serve Scheduling:
In this scheduling algorithm, the scheduler picks the threads that arrive first
in the runnable queue. Observe the following table:
Threads Time of Arrival
t1 0
t2 1
t3 2
t4 3
SleepExample.java
public class SleepExample {
public static void main(String[] args) {
System.out.println("Start");
try {
Thread.sleep(2000); // Pause for 2000 milliseconds (2 seconds)
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println("End");
}
}
TestSleepMethod1.java
class TestSleepMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{Thread.sleep(500);}
catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();
t1.start();
t2.start();
}
}
Thread Priority in Java
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
1. // Importing the required classes
2. import java.lang.*;
3.
4. public class ThreadPriorityExample extends Thread
5. {
6. public void run()
7. {
8. System.out.println("Inside the run() method");
9. }
10. public static void main(String argvs[])
11. {
12. ThreadPriorityExample th1 = new ThreadPriorityExample();
13. ThreadPriorityExample th2 = new ThreadPriorityExample();
14. ThreadPriorityExample th3 = new ThreadPriorityExample();
15. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
16. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
17. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
18. th1.setPriority(6);
19. th2.setPriority(3);
20. th3.setPriority(9);
21. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
22. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
23. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
24. System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
25. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
26. Thread.currentThread().setPriority(10);
27. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
28. }
29. }
Joining Threads in Java
The join() method in Java is provided by the java.lang.Thread class that
permits one thread to wait until the other thread to finish its execution.
Suppose th be the object the class Thread whose thread is doing its
execution currently, then the th.join();
1. import java.io.*;
class ThreadJoin extends Thread
2. {
3. public void run()
4. {
5. for (int j = 0; j < 2; j++)
6. {
try
7. {
Thread.sleep(300);
8. System.out.println("The current thread name is: " + Thread.currentThread().getName());
9. }
10. catch(Exception e)
11. {
12. System.out.println("The exception has been caught: " + e);
13. }
14. System.out.println( j );
15. }
16. }
17. }
18. public class ThreadJoinExample
19. {
20. public static void main (String argvs[])
21. {
22. ThreadJoin th1 = new ThreadJoin();
23. ThreadJoin th2 = new ThreadJoin();
24. ThreadJoin th3 = new ThreadJoin();
25. th1.start();
26. try
27. {
28. System.out.println("The current thread name is: "+ Thread.currentThread().getName());
29. th1.join();
30. }
31. catch(Exception e)
32. {
33. System.out.println("The exception has been caught " + e);
34. }
35. th2.start();
36. try
37. {
38. System.out.println("The current thread name is: " + Thread.currentThread().getName());
39. th2.join();
40. }
41. catch(Exception e)
42. {
43. System.out.println("The exception has been caught " + e);
44. }
45. h3.start();
46. }