0% found this document useful (0 votes)
0 views

ThreadControlExample.java

The document presents a Java program that demonstrates thread creation and control using a custom thread class 'MyThread'. It shows how to start multiple threads, wait for their completion using the join() method, and check their status. The program outputs messages indicating the start, progress, and completion of each thread.

Uploaded by

Shristi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

ThreadControlExample.java

The document presents a Java program that demonstrates thread creation and control using a custom thread class 'MyThread'. It shows how to start multiple threads, wait for their completion using the join() method, and check their status. The program outputs messages indicating the start, progress, and completion of each thread.

Uploaded by

Shristi Patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class MyThread extends Thread {

private String threadName;

MyThread(String name) {
this.threadName = name;
}

// The run method contains the code that constitutes a new thread.
public void run() {
System.out.println(threadName + " is starting.");
try {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " is running, count: " + i);
Thread.sleep(1000); // Sleep for 1 second.
}
} catch (InterruptedException e) {
System.out.println(threadName + " was interrupted.");
}
System.out.println(threadName + " has finished.");
}
}

public class ThreadControlExample {


public static void main(String[] args) {
// Creating threads
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");

// Start the threads


t1.start();
t2.start();
t3.start();

try {
// Use join() to wait for t1 to finish before starting the next thread
t1.join();
System.out.println("t1 joined, starting t2.");

t2.join();
System.out.println("t2 joined, starting t3.");

t3.join();
System.out.println("t3 joined, all threads finished.");

} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}

// Check if the threads are alive


System.out.println("Is t1 alive? " + t1.isAlive());
System.out.println("Is t2 alive? " + t2.isAlive());
System.out.println("Is t3 alive? " + t3.isAlive());

System.out.println("Main thread finished.");


}
}

You might also like