Multithreading in Java - Study24x7
Social learning Network
study24x7

Default error msg

Login

New to Study24x7 ? Join Now
Already have an account? Login

Multithreading in Java

Updated on 15 February 2020
study24x7
Java Object oriented programmi
7 min read 3 views
Updated on 15 February 2020

Multithreading and multiprocessing both are used to achieve multitasking in java. When two or more threads run simultaneously then we can say that this is multithreading. It is used for maximum utilization of CPU.


Multithreaded applications are the applications where two or more threads run concurrently. Hence it is also known as Concurrency in Java. Each thread runs parallel to each other. Threads don't allocate separate memory areas. Hence it saves memory. Also, context switching between threads does not take more time than the process. 

Multithreading is better than multiprocessing because threads use a shared memory area. Context-switching between the threads is easy and it does not take more time than the process. 


Thread in java can be created by extending Thread class or by implementing the runnable interface: 1. Extending the Thread class 2. Implementing the Runnable Interface 


1-Thread creation by extending thread class


Thread in java can be created by extending the java.lang.Thread class. In this, we create an object of our class and then call start() method so that thread execution can be started. The method start() invokes the run() method on the Thread object.


Example- 


package Java_Test; public class ThreadCreation extends Thread { 

public void run() { 

try { 

System.out.println ("Thread no" + 

Thread.currentThread().getId() + " is running"); 


} catch (Exception e) { 

System.out.println ("Exception occurs"); } 


public static void main(String[] args) { 

for(int i=0;i<7;i++) { 

ThreadCreation th=new ThreadCreation(); //It internally invokes run() method th.start(); } 


}


Output- 


Thread no 8 is running

Thread no 13 is running

Thread no 11 is running

Thread no 12 is running

Thread no 10 is running

Thread no 14 is running

Thread no 9 is running 


2-Thread creation by implementing the Runnable Interface- 


Thread in java can also be created by implementing the java.lang.Runnable interface. In this, we create an object of thread class and call start() method on this object. 


Example-

 

package Java_Test; 

class ThreadCreation implements Runnable { 

public void run() { 

try { 

System.out.println("Thread no " + Thread.currentThread().getId() + " is running"); 

} catch (Exception e) { 

System.out.println("Exception occurs"); } } public static void main(String[] args) { for (int i = 0; i < 7; i++) { 

Thread th = new Thread(new ThreadCreation()); th.start(); } } }


Output-


Thread no 8 is running

Thread no 9 is running

Thread no 12 is running

Thread no 10 is running

Thread no 11 is running

Thread no 13 is running

Thread no 14 is running 



study24x7
Write a comment...
Related Posts