Java Multithreading - class Thread
Multi Threading and Concurrency
Multi Threading is a concept by which multiple activities can be executed at the same time in different lines of execution. Each line of execution is called the thread
In a single core processor machine, the CPU time will be shared by the threads running in parallel. This is used to reduce the overall idle time like waiting for user input, waiting for network data or waiting for something else. Also, it also helps which activities should be given higher priority by using Thread priorities.
In a multiple core processor machine, concurrency support in Java helps to run different threads in different processor cores and thus utilizing the speed of all the cores.
Java Threads
Thread is a line of execution. A Thread can be started in Java using the class Thread
Sometimes, a thread can be created by
- extending the class Thread
- implement the interface Runnable and passing Runnable implementation reference to the Thread constructor
Java Thread Example - Extending class Thread
public class ThreadExample extends Thread{
String threadName;
public ThreadExample(String name){
this.threadName=name;
}
public void run(){
System.out.println("Inside thread: " + threadName);
}
public static void main(String a[]){
ThreadExample thread1= new ThreadExample("Thread1");
ThreadExample thread2= new ThreadExample("Thread2");
ThreadExample thread3= new ThreadExample("Thread3");
ThreadExample thread4= new ThreadExample("Thread4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
Please note that the output displayed below varies from time to time based on when the individual threads start
Output - Extending class Thread
Inside Runnable thread: Thread3 Inside Runnable thread: Thread4 Inside Runnable thread: Thread2 Inside Runnable thread: Thread1