同步Java中的两个方法 [英] Synchronizing two methods in Java

查看:34
本文介绍了同步Java中的两个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂这样的课:

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 中执行此操作?

I want the foo() method to wait until the draw method is finished and vice versa. How can I do this in Java?

问候

推荐答案

使方法同步.

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

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

或者在同一个对象上同步.

Or synchronize on the same object.

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");
    }
}

这篇关于同步Java中的两个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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