内部运行方法中的同步块
如果我有类似下面的内容,那么这在synchronized block
中意味着什么
synchronised (syncObject) {
基本上,它意味着只有一个线程可以在上面的块内,并且一旦一个线程完成执行,第二个线程将进入同步块同步(syncObject) 。 对? 任何人都可以用LayMan语言向我解释,这样我可以获得更好的画面吗?
private static final class Task implements Runnable { { private static Object syncObject = new Object(); public Task(Command command, BlockingQueue pool1, BlockingQueue pool2) { this.command = command; this.existPool = pool1; this.newPool = pool2; } public void run() { synchronised (syncObject) { if() { existId = existPool.take(); attributeMethod(existId); } else if() { newId = newPool.take(); attributeMethod(newId); } } } } // So I need to make this method synchronized or not? Currently I have made this synchronized private synchronized void attributeMethod(int range) { // And suppose If I am calling any other method here- sampleMethod(); } // What about this method, I need to make this synchronized as well? or not? private synchronized void sampleMethod() { }
基本上,它意味着只有一个线程可以在上面的块内,并且一旦一个线程完成执行,第二个线程将进入同步块同步(syncObject)。 对?
对!
所以我需要使这个方法同步或不同步?
不,你没有。 假设该方法仅在run()
方法的synchronized块中调用,该块将阻止多个线程同时执行该方法。 因此声明要synchronized
的方法是多余的。
但是,我应该指出一些事情:
-
当您将实例方法声明为
synchronized
,它将在this
同步; 即在Task
对象上。 但是您的synchronized
块正在同步另一个对象…syncObject
的对象。 在这种情况下,这无关紧要。 但是,如果run()
方法中的synchronized
块不存在,您会发现线程正在尝试在不同对象上进行同步…并且您不会得到互斥。 -
通过在
run()
方法的顶层同步…对执行该任务的所有线程使用单个共享syncObject
…您实际上是一次运行一个任务。 这完全否定了使用线程的任何好处。 -
最好将包含私有锁对象(例如
syncObject
)的变量声明为final
。 这避免了某些事情可能会覆盖它的可能性……导致同步失败。
不, attributeMethod
已经在synchronized
块的范围内运行; 除非您打算在此块之外同时调用它,否则无需将其标记为此类。