I have written a code which prints 1 if the number being tested is a happy number and 0 otherwise.
class Ishappy extends Thread {
private Integer num;
private Thread main;
private volatile boolean out = false;
Ishappy(int i, Thread main) {
this.main = main;
num = i;
}
void Exit() {
out = true;
}
@Override
public void run() {
while(!out && num != 1) {
if(num == 1) {
main.interrupt();
break;
}
String s = num.toString();
int temp = 0;
for(int i = 0 ; i < s.length(); i++) {
int x = Integer.parseInt(s.substring(i, i+1));
temp += x*x;
}
num = temp;
}
}
}
public class Happy_numbers {
public static void main(String[] args) {
byte path[] = null;
String s = "d:\\data.txt";
try(FileInputStream fin = new FileInputStream(s)) {
InputStreamReader in = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(in);
s = br.readLine();
int num;
while(s != null) {
num = Integer.parseInt(s);
Ishappy ishappy = new Ishappy(num,Thread.currentThread());
ishappy.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(1);
continue;
}
if(ishappy.isAlive()) {
ishappy.Exit();
System.out.println(0);
} else
System.out.println(11);
s = br.readLine();
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}catch(IOException ex){
}
}
}
but the above code always prints 11 for a happy number which means main is never getting interrupted. Whats wrong??
The contents of data.txt are
1
7
22
Out of which 1 and 7 are happy numbers whereas 22 is not.
I don’t see a need for threading here, a happy number is happy if the sum of its digits squared equals to one. if the sequence contains a number that is already tested. just terminate.
from wikipedia
It can be also further improved by using a map, or any caching technique so if a number is happy and you have calculated this number before, no need to do the same thing again. From wikipediea,
and the above code needs 435 to get all the happy numbers below 500.
So, I have made some changes to your code to allow remembering what have been calculated so far, at least for the current number.
and the output is
EDIT
I have found the reason why the main thread dosen’t get interrupted.
in the main while loop, you check the num being 1 or not, if it was one, you wont get to the if condition that checks for the value of num and based on which interrupts the main thread.
and here is Ihappy class
and the output is