Initializing two threads with the same instance of a runnable

前端 未结 4 1804
眼角桃花
眼角桃花 2020-11-29 05:39

Is it bad programming to initialize two threads with the same instance of a runnable? What difference would it make to initialize with separate instances of a runnable, and

4条回答
  •  情话喂你
    2020-11-29 06:12

    It's absolutely fine to do it so long as the code you're running is designed to support that. Not only will it save some memory by having a single instance instead of multiple instances, but if those threads are trying to communicate via shared data, then it may be absolutely required!

    Admittedly communicating via shared state is where threading often gets tricky, so this needs to be done carefully, but from the point of view of the threading system itself, there's absolutely no problem in having two threads call the run method of a single Runnable instance.

提交回复
热议问题