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

前端 未结 7 1302
温柔的废话
温柔的废话 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:58

    Well you could theoretically call the run method itself without problem (after all it is public). But that doesn't mean one should do it. So basically there's no reason to do this, apart from adding negligible overhead to the thread calling run(). Well except if you use the instance multiple times calling new Thread - although I'm a) not sure that's legal with the threading API and b) seems completely useless.

    Also your createThreadQueue doesn't work. synchronized on a non-static method synchronizes on the instance object (ie this), so all three threads will run in parallel.

提交回复
热议问题