I got this exercise at uni:
Write a program that declares a shared integer counter and then creates two threads, one of which attempts to increment the counter 1000 times and the other attempts to decrement the counter 1000 times. When each thread has finished looping, it should print out the final value of the counter. (Hint: You will need to define a Counter class. Why?) What do you think the output should be? Did the program work as you expected? Try running the program repeatedly to see if you always get the same result.
I ran the program expecting the final result to be zero, but it actually outputs a different number between 0 and 1000 each time. Can anyone tell me why? Thanks.
public class Counter
{
private int val;
public Counter()
{
val = 0;
}
public void increment()
{
val = val + 1;
}
public void decrement()
{
val = val - 1;
}
public int getVal()
{
return val;
}
}
public class IncThread extends Thread
{
private static final int MAX = 1000;
private Counter myCounter;
public IncThread(Counter c)
{
myCounter = c;
}
public void run()
{
for (int i = 0; i
以上就是Threads and shared counters in java的详细内容,更多请关注web前端其它相关文章!