Java Multithreading Tutorial
Multithreading allows concurrent execution parts of a program. Each part of a program is called thread. So, threads are light-weight processes.A thread begins inside run() method.Call start() method is used to start the execution of a thread. Start() invokes the run() method.
Java Thread Methods
Thread creation
Thread can be created using java.lang.Thread class.Thread class overrides the run() method.start() method is used to start the execution of a thread.
Exampleclass Multithreading implements Runnable{ public void run(){ System.out.println("My thread is in running state."); } public static void main(String args[]){ Multithreading obj=new Multithreading(); Thread sobject =new Thread(obj); sobject.start(); } }
Java Multithreading Example
class MultithreadingDemo extends Thread { public void run() { try { // Displaying the thread that is running System.out.println ("Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println ("Exception is caught"); } } } // Main Class public class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i=0; i<8; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } } }
Output:
Thread 8 is running Thread 9 is running Thread 10 is running Thread 11 is running Thread 12 is running Thread 13 is running Thread 14 is running Thread 15 is running