在Java中同步两个方法

时间:2014-06-21 12:08:02

标签: java multithreading synchronization

我有一个类似这样的课程:

public class IClass{

   public void draw(){...};  //is called periodically by the rendering thread
   public void foo(){...};    //is called asynchronously from another Thread(it could be an onTouchEvent() method for example)
}

我希望foo()方法等到draw方法完成,反之亦然。我怎么能用Java做到这一点?

问候

2 个答案:

答案 0 :(得分:4)

使方法同步。

public synchronized void draw() {   System.out.println("draw"); }

public synchronized void foo() {    System.out.println("foo"); }

或同步对象。

private static final Object syncObj = new Object();

public void draw() {
    synchronized (syncObj) {
        System.out.println("draw");
    }
}

public void foo() {
    synchronized (syncObj) {
        System.out.println("foo");
    }
}

答案 1 :(得分:0)

在方法上放置synchronized意味着线程必须在输入该方法之前获取对象实例上的锁定,因此如果您有两个标记为synchronized的不同方法,则输入它们的线程将争用相同的锁定,并且一旦一个线程获得锁定,所有其他线程将被禁止在同一个锁上同步的所有方法。因此,为了使两个方法同时运行,它们必须使用不同的锁,如下所示:

public class IClass {

      private final Object lockDraw = new Object();
      private final Object lockFoo = new Object();

      public void draw() {
          synchronized(lockDraw) {
             //method draw
          }
      }

      public void foo() {
          synchronized(lockFoo) {
             //method foo
          }
      }
}

Both methods lock the same monitor. Therefore, you can't simultaneously execute them on the same object from different threads (one of the two methods will block until the other is finished).