Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
Now Reading
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Java was introduced to the world for the first time in 1990. Since then, it has been widely used to create various applications. Naturally, the IT industry relies heavily on Java to offer its products to customers.
To become a successful computer science professional, it is necessary to grasp the fundamentals of Java. Thread in Java is one such topic that should be well comprehended if one wants to work as a computer scientist.
This article deals with several concepts in a Java Thread. It aims at covering the concepts of multitasking, the different types of multitasking, the creation of a thread in Java, how to create threads in Java, multithreading in Java, and much more. Read on to know more!
Multiple processes execute simultaneously in process-based multitasking. Each of them has to own instance of a program. In Java, one can carry out process-based multitasking using threads.
A thread is a lightweight process that exists within a process and shares its resources. Multiple threads can execute within a single program. This allows for concurrency.
Here is an example of process-based multitasking using threads in Java:
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
System.out.println("Thread " + name + " is running.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + name + " is finished.");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
}
}
Thread-based multitasking is a type of multitasking. Here, multiple threads run together within a single process. In Java, you can create threads by extending the Thread class. Another way is by implementing the Runnable interface.
Let us take a look at thread-based multitasking in Java:
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
System.out.println("Thread " + name + " is running.");
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + name + " is finished.");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
}
}
A thread in Java is a lightweight sub-process or an independent path of execution within a program. A thread runs concurrently with other threads, sharing the same memory space and resources of the program. However, it can execute independently and parallelly with threads.
Each Java program starts with a main thread. This main thread creates and manages other threads as per need. Threads can be created by extending the “Thread” class or implementing the Runnable interface. The runnable interface provides a “run()” method that contains the code to be executed by the thread.
Java threads are commonly used in applications that must be executed simultaneously with multiple other tasks. Such tasks include user interfaces, network servers, and multimedia applications. Threads can significantly enhance the performance and responsiveness of an application. They do it by allowing it to execute multiple tasks simultaneously while sharing resources efficiently.
Threads are used in Java to ensure concurrent execution of multiple tasks within a single program. They allow multiple parts of a program to run simultaneously. This makes the program more efficient and responsive. Some of the main reasons why threads are used in Java include:
In Java, a new thread is in the "new" state when an instance of the “Thread” class is created. However, the “start()” method has not yet been called on that instance. In the "new" state, the thread is not considered alive. Therefore, it cannot be scheduled for execution.
Here is a thread in Java example in the "new" state:
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
System.out.println("Thread " + name + " is running.");
}
public static void main(String[] args) {
MyThread thread = new MyThread("MyThread");
System.out.println("Thread state: " + thread.getState()); // Output: "Thread state: NEW"
}
}
Here are the two active states of a thread in Java:
1. Runnable State
A thread is in the Runnable state when it has been started, is executing, or is ready to execute but has not been given CPU time yet.
2. Running State
In Java, the running state of a thread is when the Thread object's “run()” method is executed. In other words, the thread is actively performing its task.
A thread is in a Blocked state while waiting for a monitor lock to be released. This can happen when a thread tries to access a synchronized block of code currently being held by another thread.
Example:
A thread in the "TIMED_WAITING" state is one in which a thread waits for a specific amount of time to elapse. This is either because it has called the “sleep() method” or because it is waiting for a lock to become available.
Here is an example code of a timed waiting thread in Java:
In Java, a thread enters the "Terminated" state when its “run() method” has completed execution and has stopped running. Once a thread enters the Terminated state, it cannot be restarted or resumed.
The main thread is the first one created when a Java application commences. It is created by the Java Virtual Machine (JVM). It executes the “main()” method of the application. The main thread is slightly different from other threads since it is the only one to create other threads. The main thread terminates when the “main()” method completes. Then the JVM shuts down. This terminates all other threads that are still running.
The main thread can carry out activities such as initializing the application, creating other threads, and waiting for those threads to complete. It can also be used to handle uncaught exceptions that occur in other threads.
It is to be noted that the main thread is just like any other thread in Java. It can be controlled and manipulated in the same way.
For instance, you can use the “Thread.sleep()” method to pause the main thread for a certain amount of time. Alternatively, you can use synchronization mechanisms to coordinate its execution with other threads.
Here are some ways how to create a thread in Java:
Here is an example code for creating a thread by extending the Thread class in Java:
public class MyThread extends Thread {
public void run() {
System.out.println("Thread is running.");
for (int i = 0; i < 1000000000; i++) {
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
Here is an example of creating a thread by implementing the Runnable interface in Java:
public class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running.");
for (int i = 0; i < 1000000000; i++) {
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
public class PriorityExample implements Runnable {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + " is running: " + i);
}
}
public static void main(String[] args) {
PriorityExample pe = new PriorityExample();
Thread t1 = new Thread(pe, "Thread 1");
Thread t2 = new Thread(pe, "Thread 2");
Thread t3 = new Thread(pe, "Thread 3");
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
Here is an example code snippet showing some of the commonly used constructors in the Thread class:
public class ThreadConstructorsExample implements Runnable {
public void run() {
System.out.println("Thread is running.");
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadConstructorsExample());
t1.start();
Thread t2 = new Thread(new ThreadConstructorsExample(), "MyThread");
t2.start();
Thread t3 = new Thread();
t3.start();
Thread t4 = new Thread("AnotherThread");
t4.start();
}
}
Multithread in Java allows multiple threads to run concurrently within the same program. A thread is an independent unit of execution. This runs concurrently with other threads. They share the same resources, like memory and CPU time. In Java, threads can be created by extending the Thread class or implementing the Runnable interface.
A thread deadlock is a situation where two or more threads are blocked. This is because they are waiting for each other to release the resources that they need to proceed. In Java, deadlock can be handled in many ways. Some of the ways are as follows:
Here's an example that demonstrates some of the commonly used methods of the Thread class in Java:
public class ThreadMethodsExample extends Thread {
public void run() {
System.out.println("Thread is running.");
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new ThreadMethodsExample();
System.out.println("Thread name: " + t1.getName());
t1.setName("MyThread");
System.out.println("Thread name: " + t1.getName());
System.out.println("Thread priority: " + t1.getPriority());
t1.setPriority(Thread.MAX_PRIORITY);
System.out.println("Thread priority: " + t1.getPriority());
System.out.println("Is thread alive? " + t1.isAlive());
t1.join();
System.out.println("Is thread alive? " + t1.isAlive());
System.out.println("Thread state: " + t1.getState());
}
}
This tutorial has discussed everything related to a thread in Java. We hope that this will act as a guide for your learning endeavors. Other than trying to master such areas from tutorials like these, you could also consider enrolling in a course that will prepare you to take on the challenges of the industry with ease. Online learning platforms like upGrad can help you become job-ready with industry-relevant curricula and real-world projects.
1. What is the difference between process and thread?
A process is an independent unit of execution. It has its own memory space. A thread is a lightweight process. This shares the same memory space as the parent process.
2. What is synchronization in Java?
Synchronization is the process of controlling access to shared resources. This is done in a multithreaded environment. In Java, synchronization is achieved using the “synchronized” keyword or locks.
3. What is a race condition in Java?
A race condition in Java occurs when two or more threads access a shared resource and try to modify it simultaneously. This might result in unpredictable behavior.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...