All,
For the life of me I cannot get this program to compile. The error message "error: non-static variable this cannot be referenced from a static context" occurs on lines 23 and 24.
Here is the entire program:
public class ThreadTest {
public static int x = 0;
public class Counter implements Runnable {
private int i;
private int temp;
public void run() {
for (i=0; i<10; i++) {
temp = x + 1;
x = temp;
}
} //End run()
} //End class Counter
public static void main (String[] args){
Counter myCounter1 = new Counter();
Counter myCounter2 = new Counter();
Thread threadA = new Thread(myCounter1);
Thread threadB = new Thread(myCounter2);
threadA.start();
threadB.start();
System.out.println("The final value of x is: " + x);
} //End main()
} //End class ThreadTest
If anyone could get this working and explain what I'm doing wrong I'd appreciate it. I know the difference between static and non-static, but I'm just not seeing the problem here.
I'm trying implement the program illustrated here: http://www.medicalelectronicsdesign.com/sites/default/files/image/hobbs-fig4.jpg
And described as follows:
Here, two threads increment the global variable x. Reading the code, it appears that, depending how the threads interleave during their execution, x will have a value between 10 and 20 at the end of the program. The author has tested this program 10,000 times and, as expected, each time a value between 10 and 20 has resulted. For many years, this example was used as a class exercise—until an error was discovered. In fact, x can end up with values as small as 2.
The full article is here:
http://www.medicalelectronicsdesign.com/article/build-and-validate-safety-medical-device-software
Thanks for your help,
Bill