Due Thursday, April 1, 1999
Part 1:
Write an interface DoubleReceiver with one method
public void SetValue(double val);
Write a class, SinCalculator, which extends Thread and has a constructor which takes a double and a DoubleReceiver as parameters. The constructor starts the thread which calculates the sin of the first argument to the constructor and sends it to the second argument of the constructor.
Write a class, CosCalculator, which is similar to SinCalculator but instead calculates the cos function.
Write an applet, synctest1, which has three buttons on the bottom called One, Many, and Reset. The applet displays the values of three variables, Count1 an integer, Count2 a double, and Sum a double. All of these are initially 0. The applet should implement DoubleReceiver. Its SetValue method should add the square of the value passed to it to Sum, increment count2 by 0.5, and call repaint.
The One button should generate a random value between 0 and 1 using Math.random, increment Count1 and create two threads, one of type SinCalculator and one of type CosCalculator. It should pass to these the random number generated and itself.
The Many button should do the same thing as pushing the One button 100 times.
The Reset button should set the three variables: Count1, Count2, and Sum to 0 and call repaint.
Try out the applet and see if you can get it to fail and report your results. It fails if the value of Sum is not equal to the value of Count1 to at least 5 decimal places.
Part 2:
Copy synctest1.java into synctest2.java and modify it as follows. Replace the SetValue method with
public void SetValue(double v) {
double temp;
temp = Sum;
temp = temp + v*v;
Sum = temp;
Count2 = Count2 + 0.5;
repaint(100);
}
Try again to make the applet fail and report your results.
Part 3:
Copy synctest2.java into synctest3.java and modify it as follows. Insert the following method in the applet:
public void mysleep(int n) {
try {
Thread.sleep(n);
} catch (InterruptedException e) {}
}
and insert a call to mysleep(100) in SetValue
before the line Sum = temp. Try the applet again and
see what happens.
Try the applet with different values of the sleeptime and determine the smallest value for which you can make the applet fail. Report your results.
Part 4:
Copy synctest3.java into synctest4.java. Use a value
of the sleep time which makes it easily fail. Now replace SetValue
with
public synchronized void SetValue(double v)
and try to
make the applet fail. Report your results.
Part 5: (Extra credit, but not much)
Make a new applet which is like synctest4 which has a slider to
control the sleep time and a way to turn on or off the synchronization.
Turn in your source code and your report of the results. Your report should contain a concluding paragraph indicating what you learned from this assignment. Put the applets on the web with links from your course web site.