87
How to perform single task by multiple threads in Java?
If you have to perform a single task by many threads, have only one run() method. For example:
Program of performing single task by multiple threads
FileName: TestMultitasking1.java
Output:
task one task one task one
Program of performing single task by multiple threads
FileName: TestMultitasking2.java
Output:
task one task one
Note: Each thread run in a separate callstack.
How to perform multiple tasks by multiple threads (multitasking in multithreading)?
If you have to perform multiple tasks by multiple threads,have multiple run() methods.For example:
Program of performing two tasks by two threads
FileName: TestMultitasking3.java
Output:
task one task two
Same example as above by anonymous class that extends Thread class:
Program of performing two tasks by two threads
FileName: TestMultitasking4.java
Output:
task one task two
Same example as above by anonymous class that implements Runnable interface:
Program of performing two tasks by two threads
FileName: TestMultitasking5.java
Output:
task one task two
Printing even and odd numbers using two threads
To print the even and odd numbers using the two threads, we will use the synchronized block and the notify() method. Observe the following program.
FileName: OddEvenExample.java
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Next TopicGarbage Collection