Basic Multithreading Program 1
Basic Multithreading Program 1
MultiThreadingDemo
Click Finish.
com.example.threads
Click Finish.
MyThread
5. Click Finish.
try {
} catch (InterruptedException e) {
e.printStackTrace();
ThreadDemo
5. Click Finish.
package com.example.threads;
t1.setName("Thread 1");
t2.setName("Thread 2");
Thread 1 - Count: 1
Thread 2 - Count: 1
Thread 1 - Count: 2
Thread 2 - Count: 2
Thread 1 - Count: 3
Thread 2 - Count: 3
...
Two threads (t1 and t2) run independently and print numbers from 1 to 5.
Multithreading is a feature in Java that allows multiple parts of a program (threads) to run
simultaneously. This improves performance and efficiency.
For example:
A video player can play video and receive user input at the same time.
A web browser can load pages and allow scrolling at the same time.
A thread is like a separate worker running a task in a program. In Java, you can create threads using
two methods:
Let's create a simple multithreading program where two threads run simultaneously and print
numbers.
We create a class that extends Thread and overrides the run() method.
try {
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Thread.sleep(1000): Makes the thread pause for 1 second to simulate processing time.
We create two threads inside the main method and start them.
t1.setName("Thread 1");
t2.setName("Thread 2");
Wrong way: Calling run() directly → Runs like a normal method, NOT a thread.
Since the threads run independently, the output may vary each time:
Thread 1 - Count: 1
Thread 2 - Count: 1
Thread 1 - Count: 2
Thread 2 - Count: 2
Thread 1 - Count: 3
Thread 2 - Count: 3
Thread 1 - Count: 4
Thread 2 - Count: 4
Thread 1 - Count: 5
Thread 2 - Count: 5
Instead of extending Thread, you can implement Runnable for better flexibility.
package com.example.threads;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Step 2: Create Threads Using Thread Class
package com.example.threads;
🔹 Use Runnable when possible because Java doesn’t support multiple inheritance.
7️ Summary of Steps
Step Action