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

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

问题描述

我一直认为在实现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方法,你可能会创建一个de -facto线程队列,例如通过这样做:

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 的方法是完全没有意义的,除非你想要在多个线程之间共享 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.

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

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