多线程都要读写的变量假设为:serverTime
A线程要做的:网络请求服务器时间,并在请求成功后赋值给serverTime
B线程要做的:直到网络返回时间,然后使用该时间,不然一直等待
A线程:
在网络请求返回的onSeccess
方法中:
synchronized (lock) {
serverTime = response.getCurrentTime(); // 获得网络请求的时间
// 通知其他线程我这里ok了
lock.notifyAll();
}
B线程:
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
while (serverTime == 0) {
try {
lock.wait(500); //every 500ms release lock
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Custom logic : use the serverTime
Slog.d(TAG, "TimeStamp is " + serverTime);
}
}
}).start();