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 threadsFileName: TestMultitasking1.java Test it NowOutput: task one task one task one Program of performing single task by multiple threadsFileName: TestMultitasking2.java Test it NowOutput: 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 Test it NowOutput: 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 Test it NowOutput: 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 Test it NowOutput: task one task two Printing even and odd numbers using two threadsTo 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 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India