Multithreading in Java
This article explains how to perform a single and multiple tasks using multiple threads.
Performing single task
If we need to perform a single task using multiple threads then we need to use only one/single run() method.
Example
In this example, we simply extend the thread and perform a single task using multiple threads.
- class MultithreadEx1 extends Thread
- {
- public void run()
- {
- System.out.println("Start task one");
- }
- public static void main(String args[])
- {
- MultithreadEx1 th1 = new MultithreadEx1();
- MultithreadEx1 th2 = new MultithreadEx1();
- MultithreadEx1 th3 = new MultithreadEx1();
- th1.start();
- th2.start();
- th3.start();
- }
- }
Output
Example 2
In this example we use the Runnable interface instead of extending threads.
- class MultithreadEx2 implements Runnable
- {
- public void run()
- {
- System.out.println("Start task one");
- }
- public static void main(String args[])
- {
- Thread th1 = new Thread(new MultithreadEx2());
- Thread th2 = new Thread(new MultithreadEx2());
- Thread th3 = new Thread(new MultithreadEx2());
- th1.start();
- th2.start();
- th3.start();
- }
- }
Output
Performing multiple tasks
To perform multiple tasks by multiple threads, we need to use multiple run() methods.
Example 1
In this example; we need to extend the thread to perform multiple tasks.
- class MultithreadEx3 extends Thread
- {
- public void run()
- {
- System.out.println("Start task one");
- }
- }
- class MultithreadEx4 extends Thread
- {
- public void run()
- {
- System.out.println("Start task two");
- }
- }
- class Run
- {
- public static void main(String args[])
- {
- MultithreadEx3 th1 = new MultithreadEx3();
- MultithreadEx4 th2 = new MultithreadEx4();
- th1.start();
- th2.start();
- }
- }
Output
Example 2
In this example, we use an anonymous class that extends the Thread class.
- class Check
- {
- public static void main(String[] args)
- {
- Thread th1 = new Thread()
- {
- public void run()
- {
- System.out.println("Start task one");
- }
- };
- Thread th2 = new Thread()
- {
- public void run()
- {
- System.out.println("Start task two");
- }
- };
- th1.start();
- th2.start();
- }
- }
Output
Example 3
In this example, we use an anonymous class that implements the Runnable interface.
- class Check1
- {
- public static void main(String[] args)
- {
- Runnable run1 = new Runnable()
- {
- public void run()
- {
- System.out.println("Start task one");
- }
- };
- Runnable run2 = new Runnable()
- {
- public void run()
- {
- System.out.println("Start task two");
- }
- };
- Thread th1 = new Thread(run1);
- Thread th2 = new Thread(run2);
- th1.start();
- th2.start();
- }
- }
Output