内部运行方法中的同步块

时间:2012-08-21 01:07:14

标签: java multithreading

如果我有类似下面的内容,那么synchronized block

中的意思是什么
synchronised (syncObject) {

基本上,这意味着只有一个线程可以在上面的块中,一旦一个线程完成执行,第二个线程就会进入同步块 synchronized(syncObject)。对? 任何人都可以用LayMan语言向我解释,以便我能得到更好的画面吗?

private static final class Task implements Runnable {
{
  private static Object syncObject = new Object();

    public Task(Command command, BlockingQueue<Integer> pool1, BlockingQueue<Integer> 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() {


}

2 个答案:

答案 0 :(得分:8)

  

基本上,它意味着只有一个线程可以在上面的块中,并且一旦一个线程完成执行,第二个线程将进入同步块同步(syncObject)。正确?

右键!

  

所以我需要同步或不同步这个方法吗?

不,不。假设该方法仅在run()方法的同步块内调用,该块将阻止多个线程同时执行该方法。因此,将方法声明为synchronized是多余的。

但是,我应该指出一些事情:

  • 当您将实例方法声明为synchronized时,它将在this上同步;即在Task对象上。但是您的synchronized块正在同步另一个对象... syncObject中的对象。在这种情况下,这无关紧要。但是,如果synchronized方法中的run()块不存在,您会发现线程正在尝试在不同对象上进行同步...并且您不会互相排斥。

  • 通过run()方法的顶层同步...对执行该任务的所有线程使用单个共享syncObject ...您实际上正在运行任务一次。这完全否定了使用线程的任何好处。

  • 最好将包含私有锁对象(例如syncObject)的变量声明为final。这可以避免某些事情可能会覆盖它......导致同步失败。

答案 1 :(得分:1)

不,attributeMethod已在synchronized块的范围内运行;除非你打算在这个区块之外同时调用它,否则不需要标记它。