我一直认为,在实现Runnable的java类中同步run方法是多余的。我试图弄清楚为什么人们这样做:
public class ThreadedClass implements Runnable{
//other stuff
public synchronized void run(){
while(true)
//do some stuff in a thread
}
}
}
这似乎是多余且不必要的,因为它们正在为另一个线程获取对象的锁。更确切地说,他们明确表示只有一个线程可以访问run()方法。但是由于它是run方法,它本身不是自己的线程吗?因此,只有它可以访问自身,并且不需要单独的锁定机制?
我在网上找到了一个建议,即通过同步运行方法,您可以通过以下方式例如创建事实上的线程队列:
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方法。有什么想法为什么或为什么不应该同步运行方法?
同步a的run(
)方法Runnable
是完全没有意义的,除非您要Runnable
在多个线程之间共享,并且希望按顺序执行这些线程。基本上这是一个矛盾。
从理论上讲,还有另一种更为复杂的场景,您可能需要同步该run()
方法,该场景再次涉及Runnable
在多个线程之间共享,但也使用wait()
和notify()
。我有21年以上的Java经验,从未见过。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句