Threads and shared counters in java

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前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏