Should you synchronize the run method? Why or why not?(你应该同步运行方法吗?为什么或者为什么不?)
问题描述
我一直认为在实现 Runnable 的 java 类中同步 run 方法是多余的.我想弄清楚人们为什么这样做:
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:
public class ThreadedClass implements Runnable{
//other stuff
public synchronized void run(){
while(true)
//do some stuff in a thread
}
}
}
这似乎是多余和不必要的,因为他们正在为另一个线程获取对象的锁.或者更确切地说,他们明确表示只有一个线程可以访问 run() 方法.但是既然是run方法,那它本身不就是自己的线程吗?所以只有它自己可以访问,不需要单独的锁机制?
It seems redundant and unnecessary since they are obtaining the object's lock for another thread. Or rather, they are making explicit that only one thread has access to the run() method. But since its the run method, isn't it itself its own thread? Therefore, only it can access itself and it doesn't need a separate locking mechanism?
我在网上找到了一个建议,通过同步 run 方法,您可能会创建一个事实上的线程队列,例如这样做:
I found a suggestion online that by synchronizing the run method you could potentially create a de-facto thread queue for instance by doing this:
public void createThreadQueue(){
ThreadedClass a = new ThreadedClass();
new Thread(a, "First one").start();
new Thread(a, "Second one, waiting on the first one").start();
new Thread(a, "Third one, waiting on the other two...").start();
}
我永远不会亲自这样做,但这会引发一个问题,即为什么有人会同步 run 方法.任何想法为什么或为什么不应该同步 run 方法?
I would never do that personally, but it lends to the question of why anyone would synchronize the run method. Any ideas why or why not one should synchronize the run method?
推荐答案
同步 Runnable
的 run(
) 方法完全没有意义除非 你想在多个线程之间共享 Runnable
并且 你想按顺序执行这些线程.这基本上是一个矛盾的术语.
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.
理论上还有另一个更复杂的场景,您可能希望同步 run()
方法,这同样涉及在多个线程之间共享 Runnable
,但也使用 wait()
和 notify()
.我在 21 多年的 Java 中从未遇到过它.
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.
这篇关于你应该同步运行方法吗?为什么或者为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你应该同步运行方法吗?为什么或者为什么不?
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01