Multithreading in Java
Multithreading in Java
14
// Throwing an exception
15
System.out.println("Exception is caught");
16
}
17
}
18
}
19
20
// Main Class
21
public class Geeks
22
{
23
public static void main(String[] args)
24
{
25
int n = 8; // Number of threads
26
for (int i = 0; i < n; i++) {
27
Multithreading object
28
= new Multithreading();
29
object.start();
30
}
31
}
32
}
Output
Thread 13 is running
Thread 14 is running
Thread 12 is running
Thread 11 is running
Thread 16 is running
Thread 15 is running
Thread 18 is running
Thread 17 is running
14
// Throwing an exception
15
System.out.println("Exception is caught");
16
}
17
}
18
}
19
20
// Main Class
21
class Geeks {
22
public static void main(String[] args)
23
{
24
int n = 8; // Number of threads
25
for (int i = 0; i < n; i++) {
26
Thread object
27
= new Thread(new Multithreading());
28
object.start();
29
}
30
}
31
}
Output
Thread 12 is running
Thread 15 is running
Thread 18 is running
Thread 11 is running
Thread 17 is running
Thread 13 is running
Thread 16 is running
Thread 14 is running
Thread Class vs Runnable Interface
Sr.No
Method & Description
.
The previous methods are invoked on a particular Thread object. The following
methods in the Thread class are static. Invoking one of the static methods
performs the operation on the currently running thread.
Sr.No
Method & Description
.
Example
The following ThreadClassDemo program demonstrates some of these methods
of the Thread class. Consider a class DisplayMessage which
implements Runnable −
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
class DisplayMessage implements Runnable {
private String message;
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
This produces a different result every time you run this program −
Output
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 5
Counter --- 2
Counter --- 1
Counter --- 4
Thread Thread - 1 exiting.
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Multithreading Example with Thread Synchronization
Here is the same example which prints counter value in sequence and every
time we run it, it produces the same result.
Example
Open Compiler
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
T1.start();
T2.start();