0% found this document useful (0 votes)
3 views6 pages

Multithreading in Java

Multithreading in Java allows multiple threads to execute simultaneously, sharing a common memory area, which saves memory and reduces context-switching time. The document outlines the advantages of multithreading, the lifecycle of a thread, methods to create threads, and the concept of thread priority. It also provides examples of creating threads by extending the Thread class and implementing the Runnable interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Multithreading in Java

Multithreading in Java allows multiple threads to execute simultaneously, sharing a common memory area, which saves memory and reduces context-switching time. The document outlines the advantages of multithreading, the lifecycle of a thread, methods to create threads, and the concept of thread priority. It also provides examples of creating threads by extending the Thread class and implementing the Runnable interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

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.

Thread Lifecycle
 Home
 Multithreading
 Thread Lifecycle
Each thread has a lifecycle consisting of thread states. Let’s understand
these states.

1. New
2. Runnable
3. Running
4. Blocked/Waiting/Sleeping
5. Terminated or Dead
New
When a thread object is created using new keyword, it is in a state that is
called ‘New’ state. At this moment, only an object is created in the JVM.
Please note that the thread hasn’t started working yet.

Runnable
Remember the statment t.start(); ? We used this to start a thread, right?
So, does the thread start when this method is called on it? The answer is
no. start() method call only ensures that the thread is registered in a pool
of threads which is refered by the Thread scheduler to run a particular
thread.
This thread pool is called Runnable pool, and the threads which are there
in this pool are known to be in Runnable state.

In this state, thread is runnable, meaning it can be picked up by the thread


scheduler to run any time. But the thread is still not running.

Running
A thread is said to be in this state when the thread is actully running its
run() method code.

Blocked/Waiting/Sleeping
A thread which is running can be pushed to one of the three states:
Blocked/Waiting/Sleeping.
Blocked state is the one in which a thread is blocked for some resource or
a lock which is already acquired by another thread.

Waiting state is the one in which a thread goes after calling wait() method.

Sleeping state is the one in which a thread goes after calling sleep()
method.

All these 3 states are clubbed as one state because they are more or less
similar. In any of these states, the thread is not eligible for running.

Note -> Once a thread goes back from any of these states, it doesn’t start
running immediately. Rather it goes back to runnable pool of threads
where it is upto the scheduler when that thread will be picked to run.
Terminated or Dead
A thread goes to Terminated or Dead state when it completes its run()
method execution. Once dead, a thread cannot be run again. If someone
tries to start a dead thread, then an IllegalThreadStateException is
thrown.

How to create Thread-

There are two ways to create and manage threads:

Extending the Thread Class

You can create a thread by extending the Thread class and overriding its run() method.

public class MyThread extends Thread {


@Override
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {


MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
}

2. Implementing the Runnable Interface

Alternatively, you can create a thread by implementing the Runnable interface and passing an
instance to a Thread object.
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {


MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // Starts the thread
}
}

Thread Priority-
In Java, thread priority is an integer value that hints to the thread scheduler about the relative
importance of a thread. Threads with higher priorities are more likely to be selected for execution
before lower-priority threads. However, it's important to note that thread priority does not
guarantee the order of execution; it merely influences the thread scheduler's decision.

Thread Priority Levels

Java defines thread priorities as integer values ranging from 1 (lowest) to 10 (highest):

Thread.MIN_PRIORITY =1

 Thread.NORM_PRIORITY = 5 (default)
 Thread.MAX_PRIORITY = 10

1. // Importing the required classes


2. import java.lang.*;
3.
4. public class ThreadPriorityExample extends Thread
5. {
6.
7. // Method 1
8. // Whenever the start() method is called by a thread
9. // the run() method is invoked
10. public void run()
11. {
12. // the print statement
13. System.out.println("Inside the run() method");
14. }
15.
16. // the main method
17. public static void main(String argvs[])
18. {
19. // Creating threads with the help of ThreadPriorityExample class
20. ThreadPriorityExample th1 = new ThreadPriorityExample();
21. ThreadPriorityExample th2 = new ThreadPriorityExample();
22. ThreadPriorityExample th3 = new ThreadPriorityExample();
23.
24. // We did not mention the priority of the thread.
25. // Therefore, the priorities of the thread is 5, the default value
26.
27. // 1st Thread
28. // Displaying the priority of the thread
29. // using the getPriority() method
30. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
31.
32. // 2nd Thread
33. // Display the priority of the thread
34. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
35.
36. // 3rd Thread
37. // // Display the priority of the thread
38. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
39.
40. // Setting priorities of above threads by
41. // passing integer arguments
42. th1.setPriority(6);
43. th2.setPriority(3);
44. th3.setPriority(9);
45.
46. // 6
47. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
48.
49. // 3
50. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
51.
52. // 9
53. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
54.
55. // Main thread
56.
57. // Displaying name of the currently executing thread
58. System.out.println("Currently Executing The Thread : " + Thread.currentT
hread().getName());
59.
60. System.out.println("Priority of the main thread is : " + Thread.currentThre
ad().getPriority());
61.
62. // Priority of the main thread is 10 now
63. Thread.currentThread().setPriority(10);
64.
65. System.out.println("Priority of the main thread is : " + Thread.currentThre
ad().getPriority());
66. }
67. }
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

You might also like