This is my code for this task after finding the answer in the help section.
public void showWarning(){
this.stop();
}
public void run(){
while(isAlive()){}
}
What I don't understand is , how does this thread ever call the showWarning method?
From what I can gather the run method will run indefinitely without calling showWarning.
Some insight please.
Confused !?
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
Ivan
21 April 2020, 12:06
Would you please provide the whole code in order to review it?
0
Ntuthuko Xaba
21 April 2020, 18:00
public class Solution {
public static List<Thread> threads = new ArrayList<>(5);
static {
threads.add(new T1());
threads.add(new T2());
threads.add(new T3());
threads.add(new T4());
threads.add(new T5());
}
public static void main(String[] args) {
}
0
Ntuthuko Xaba
21 April 2020, 18:00
public static class T1 extends Thread{
public void run(){
while(true){
try{
System.out.println("I am running!");
Thread.sleep(1000);
}catch (InterruptedException e){}
}
}
}
public static class T2 extends Thread{
public void run(){
while(true){
try{
System.out.println("I am running!");
Thread.sleep(1000);
}catch (InterruptedException e){
System.out.println("InterruptedException");
}
}
}
}
public static class T3 extends Thread{
public void run(){
while(true){
try{
System.out.println("Hurray");
Thread.sleep(500);
}catch (InterruptedException e){ }
}
}
}
public static class T4 extends Thread implements Message{
public void showWarning(){
this.stop();
}
public void run(){
while(isAlive()){}
}
}
public static class T5 extends Thread{
public void run(){
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int count = 0;
int i = 0;
while(true) {
String temp = reader.readLine();
if (temp.isEmpty()) {
break;
} else if (temp.equals("N")) {
System.out.println(count);
break;
} else {
i = Integer.parseInt(temp);
count = count + i;
}
}
} catch(Exception e){}
}
}
}
0
Ivan
22 April 2020, 12:02
T4 implements Message and you are overriding the showWarning method, setting it to this.stop.
You are calling the showWarning method.
Firstly you are calling the run method as it is a thread then the other part.
Not entirely certain if it runs 'run' method first and then the showWarning, or the other way around. You can try with debugger and check :)
+1
Ntuthuko Xaba
22 April 2020, 20:55
Thanks ,I need to read up on it more, hopefully by the end of the next quest it will make more sense.
0