I have looked at the answers here and none of them make sense to me. It seems like they all say not to explicitly call showWarning(). My code fails saying I have not implemented the message interface. Thread four isAlive when I start it in main() but isAlive is never true when tested within the thread4 instance itself.
Any help is appreciated.
For the codegym developers, this exercise has been a great demonstration of the law of diminishing returns and should probably be revamped.
package com.codegym.task.task16.task1632;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Solution {
public static List<Thread> threads = new ArrayList<>(5);
static {
threads.add(new Thread(new thread1()));
threads.add(new Thread(new thread2()));
threads.add(new Thread(new thread3()));
threads.add(new Thread(new thread4()));
threads.add(new Thread(new thread5()));
}
public static void main(String[] args) {
threads.get(3).start();
}
public static class thread1 implements Runnable {
@Override
public void run() {
while(true);
}
}
public static class thread2 implements Runnable {
@Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("InterruptedException");
}
}
}
public static class thread3 implements Runnable {
@Override
public void run() {
try {
while (!Thread.interrupted()) {
System.out.println("Hurray");
Thread.sleep(500);
}
} catch (Exception e) {
}
}
}
public static class thread4 extends Thread implements Message {
boolean isAlive = this.isAlive();
@Override
public void showWarning() {
if(!this.isInterrupted()) {
this.interrupt();
}
}
@Override
public void run() {
if(this.isAlive) {
showWarning();
}
}
}
public static class thread5 implements Runnable {
@Override
public void run() {
int sum = 0;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while(true) {
String inputString = reader.readLine();
if(inputString.equals("N")) {
break;
}
sum += Integer.parseInt(inputString);
}
System.out.println(sum);
} catch (IOException e) {
}
}
}
}