I'm trying to create a small program that takes two classes, a class which extends Thread and a class which implements Runnable.
I've then created a third class where I create an object of both classes, and I want to run the threads and only end the program when both threads are finished.
I've looked at the java docs and am using the .isAlive() function to check if the thread is still alive... Though this is working for my thread object which extends Thread but doesn't seem to work with the thread which implements Runnable.
public class TaskTwo extends Thread {
public void run() {
System.out.println("Thread start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Thread end");
}
public class TaskThree implements Runnable {
@Override
public void run() {
System.out.println("Runnable thread start");
try {
java.lang.Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Runnable thread end");
}
public class TaskFour {
static TaskTwo thread1 = new TaskTwo();
static TaskThree thread2 = new TaskThree();
public static void main(String[] args) {
if (thread1.isAlive() && thread2.isAlive()) {
thread1.run();
} else {
System.out.println("Threads completed");
}
}}
The error code is in the TaskFour class on the if statement line. Eclipse is telling me to create a method for isAlive() in TaskThree class and i'm unsure why it's working for the Thread and not the Runnable.
Any help would be appreciated, Thanks in advance. Sam