gpt4 book ai didi

java - Java中同步两个方法

转载 作者:行者123 更新时间:2023-12-01 18:30:43 26 4
gpt4 key购买 nike

我有一个这样的类(class):

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() 方法等待直到绘制方法完成,反之亦然。我怎样才能在Java中做到这一点?

问候

最佳答案

使方法同步。

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

关于java - Java中同步两个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24341447/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com