If you do a set amount of time, and then interrupt the process, you have an interesting question to answer:
- Did you collect enough data to answer the question?
I'll let you ponder that question, while I suggest how you could interrupt a still-calculating answer.
First, you should know ahead of time the first fifty digits of your square root, as you will need that to "know" if the answer is correct. Correctness should be independent of how long it takes, so perhaps you'll just verify the calculation once, and then hard-code the correct answer.
Second, you need to package your square root calculation algorithims in something that can be run. I would suggest that Java interface Runnable
, which forces a method with the signature
public void run() {
// your code goes here
}
Then you will have something that will blend well with a Java Thread
and you can interrupt Java threads. Once interrupted the results of a Thread, you cannot trust any calculation from within the thread (under normal circumstances).
The simplest means (and since your project is not about leveraging the newest Java technologies, but about attempting to disprove your anti-hypothesis) is to do something like
Thread solution1 = new Thread(new Runnable1());
solution1.start();
later if you find something is taking far too long
Thread.sleep(10000); // sleeps the current thread 10 seconds
solution1.interrupt();
Note that this is a very inelegant way to stop a thread, and you can't trust anything that the Runnable1
was working on afterwards.
Other, more sophisticated techniques are available, such as:
public class Runnable1 implements Runnable {
private boolean running;
public Runnable1() {
running = false;
}
public void run() {
running = true;
while (running) {
// do one step of your computation
}
}
public void shutdown() {
running = false;
}
}
The above example has tons of features which really do improve the quality of the Java code; but, be aware that quality of code is independent of proving your point. It is possible to polish code to be very nice, and forget to actually solve the problem.
The above code would then be called
Runnable1 runnable1 = new Runnable1();
Thread thread1 = new Thread(runnable1);
thread1.start
// some means of waiting
Thread.sleep(10000); // sleeps 10 seconds
runnable1.shutdown();
This technique shuts down your runnable in a known state (before the next loop iteration), and so perhaps you could then capture some intermediate data from the technique, provided that the rest of the Runnable
has a means to report an intermediate solution.