Skip to main content

Practical-36

Write a java program which creates threads using the Thread Class.

1. Introduction

Threads are a form of lightweight processes that are used in Java programming. They are used to execute multiple tasks simultaneously and allow for better use of resources as it allows different parts of a program to run simultaneously. To create threads, Java provides a special class called Thread. This class allows us to create new threads, carry out operations on the threads we have created and also allows us to control the flow of the threads. The Thread class provides several methods which can be used to create and manage threads with ease, thus making multithreading a crucial part of Java.

Code

public class Task {
public static void main(String args[]) {

Thread thread1 = new Thread(new MyNewThread("Thread-1"));
thread1.start();

Thread thread2 = new Thread(new MyNewThread("Thread-2"));
thread2.start();
}
}

class MyNewThread implements Runnable{

Thread t;
String threadName;

MyNewThread(String threadName){
t = new Thread(this,threadName);
this.threadName = threadName;
System.out.println("Thread " + threadName + " has been created");
}

@Override
public void run(){
while(true){
System.out.println("Thread: " + threadName);
}
}

}

Output

Thread Thread-1 has been created
Thread Thread-2 has been created
Thread: Thread-1
Thread: Thread-2
Thread: Thread-1
Thread: Thread-2
.
.
.
Explanation

The above code uses class Thread to create two threads - 'Thread-1' and 'Thread-2'. Both of these threads enter an infinite loop, where they keep printing out the thread's name.