Why this broken program always runs?

前端 未结 2 723
孤城傲影
孤城傲影 2021-01-22 11:29

I was trying examples from JCIP and Below program should not work but even if I execute it say 20 times it always work which means ready and number are

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-22 11:57

    What is important to keep in mind is that a broken concurrent program might always work with the right combination of JVM's options, machine architecture etc. That does not make it a good program, as it will probably fail in a different context: the fact that no concurrency issue shows up does not mean there aren't any.

    In other words, you can't prove that a concurrent program is correct with testing.

    Back to your specific example, I see the same behaviour as what you describe. But, if I remove the Thread.yield() instruction in the while loop, 3 out of 8 threads stop and print 42, but the rest don't and the program never ends.

提交回复
热议问题