你应该同步运行方法吗?为什么或者为什么不? [英] Should you synchronize the run method? Why or why not?

查看:26
本文介绍了你应该同步运行方法吗?为什么或者为什么不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为在实现 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?

推荐答案

同步 Runnablerun() 方法完全没有意义除非 你想在多个线程之间共享 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.

这篇关于你应该同步运行方法吗?为什么或者为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆