Sunday, December 10, 2017

Multithreading in Java

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU
Multitasking can be achieved by two ways:
  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)
Process-based Multitasking (Multiprocessing)

Thread-based Multitasking (Multithreading)

Each process have its own address in memory
Threads share the same address space
heavyweight
lightweight
Cost of communication between the process is high
Cost of communication between the thread is low

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.


Process is an executing instance of an application. For example, when you double click MS Word icon in your computer, you start a process that will run this MS word application.



  
Creating a thread,
1)      By extending java.lang.Thread class.

public class ThreadExtended {
public static void main(String[] arg){
//Creating a thread and starting it 
MyThread mt1 = new MyThread();
mt1.start();
}
}

class MyThread extends Thread{
public void run(){
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}




2) By implementing java.lang.Runnable interface.

public class RunnableImplementation  {

public static void main(String[] arg){
//Creating a thread and starting it 
//MyThreadRI mt = new MyThreadRI();  // Creating an instance of  MyThreadRI
//Thread thread = new Thread(mt);  // Creating a thread using Runnable implemented object
//thread.start();
// Create a thread using Java 8
Thread t1 = new Thread(()->{
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
});
t1.start();
}
}

class MyThreadRI implements Runnable{
@Override
public void run() {
// task for the thread
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}

No comments:

Post a Comment

The Hypervisor

 The hypervisor is a piece of software that runs on top of hardware infrastructure that creates a virtualization platform. The hypervisor a...