Is a static counter thread safe in multithreaded application?

后端 未结 6 759
青春惊慌失措
青春惊慌失措 2021-01-14 13:02
public class counting
{
  private static int counter = 0;

  public void boolean counterCheck(){
  counter++;
  if(counter==10)
  counter=0;
  }
}

6条回答
  •  梦毁少年i
    2021-01-14 14:01

    It's clearly not thread-safe. Consider two threads that run in perfect parallel. If the counter is 9, they'll each increment the counter, resulting in the counter being 11. Neither of them will then see that counter equal to 10, so the counter will keep incrementing from then on rather than wrapping as intended.

提交回复
热议问题