Creating multiple Threads

This java tutorial explain how to create multiple thread using Java program. Here you will find step by step process to creating multiple threads.

Creating multiple Threads

This java tutorial explain how to create multiple thread using Java program. Here you will find step by step process to creating multiple threads.

Creating multiple Threads


In this section you will learn how to create multiple thread in java. Thread is a path of execution within a program, it is a part of process. JVM allow multiple thread to run concurrently. Each and every thread has the priority or you can set or get the priority of thread. Java API provide method like setPriority() and getPriority() method to set or get the priority of thread. Thread having high priority will execute first over thread having low priority. Thread are lightweight process. There are two way to create thread in java they are as follows:

  • By implementing Runnable interface.
  • By extending Thread class.

While implementing Runnable interface or extending Thread class, you have to override run() method.

Example : Code for creating multiple thread.
public class B extends Thread {

public void run() {
System.out.println();
for (int i = 1; i <= 5; i++) {
System.out.println(" Thread name = "+ Thread.currentThread().getName());
}
}
public static void main(String[] args) {
B t1 = new B();
t1.start();

B t2 = new B();
t2.start();

B t3 = new B();
t3.start();
}

Output : When you compile and execute the program the output will be as below

Download SourceCode