MultiThreading or MultiTasking
Let us assume a class containing three functions named as fun1,fun2 and fun3. If all are called once it may take more time to execute.
In the above example fun2(), fun3() will be executed only after the complete execution of fun1().
In the above example fun2(), fun3() will be executed only after the complete execution of fun1().
Suppose fun1() is performing any input/output operations then at that time processor will be in the ideal state. If input/output operations take 60sec and also fun2() and fun3() will not be executed until 60sec are completed. To overcome this disadvantage the concept of multitasking is used.
There are two types of multitasking techniques.
1.Process based multitasking
1. Process based multitasking:In the above diagram the jobs(processors) issued by different clients will be executed at the server simultaneously. Whenever the different processors are executed simultaneously then it is called as process based multitasking. This will be achieved by using the scheduling.
Every user will have the assumption that he had his own processor.
2. Thread based multitasking:
In the above example fun1(),fun2() and fun3() can be called as threads. Which are different paths present for a single process. All the threads present within a single process will be executed simultaneously according to the time slice.
Thread based multitasking can be achieved by using the thread class or Runnable interface.
interface Runnable{ public void run(); } class Thread implements Runnable{ public void run(){ ------ ----- --- } . . . . }only there exists a single abstract method run within Runnable interface.
The thread class implements the Runnable interface. The Thread class contains some of the additional methods.i.e. for Ex: start()which will invoke the run() implicitly.
run() must contain the set of statements that need to be executed simultaneously.
run() contain the code which is treated as thread.
By default for the main function a thread will be created.
Ex:
package com.javabynataraj; public class Threadone extends Thread{ public void run(){ for(int i=1;i<=10;i++){ System.out.println("in run: "+i); } } public static void main(String[] args) { Threadone tone = new Threadone(); tone.start(); for(int i=1;i<=10;i++){ System.out.println("in main: "+i); } } }
Output:
The above example consists of two threads.. i.e.
Threadone(t1) and main(). This statements presents in the two threads will be executed according to the time slice. Generally time slice will be in terms of nanoseconds.
Always a user can't judge which thread will be executed first.