Should you synchronize the run method? Why or why not?

前端 未结 7 1312
温柔的废话
温柔的废话 2020-11-29 07:34

I have always thought that synchronizing the run method in a java class which implements Runnable is redundant. I am trying to figure out why people do this:

7条回答
  •  悲&欢浪女
    2020-11-29 07:54

    Synchronizing the run() method of a Runnable is completely pointless unless you want to share the Runnable among multiple threads and you want to sequentialize the execution of those threads. Which is basically a contradiction in terms.

    There is in theory another much more complicated scenario in which you might want to synchronize the run() method, which again involves sharing the Runnable among multiple threads but also makes use of wait() and notify(). I've never encountered it in 21+ years of Java.

提交回复
热议问题