【发布时间】:2018-07-10 00:19:54
【问题描述】:
我有几个线程同时运行,其中一些需要从 Internet 请求数据。我需要关心他们对 OkHttpClient 单例的访问同步吗?
例如,
线程1:
...
Request request = new Request.Builder()
.url("http://hell.com/siners.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Some work in Thread1
}
}
线程2:
...
Request request = new Request.Builder()
.url("http://hell.com/slutList.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// Some work in Thread2
}
}
同时 newCall().enque() 或 newCall().execute() 是否有潜在危险?
【问题讨论】:
-
你能提供更多背景信息吗,代码是可取的,只有这样才能进行适当的讨论
-
@Remario,已编辑
-
好吧,看起来不错,在我回答之前,你考虑过改造吗?
-
检查我无聊的答案!
-
我想用 Retrofit 但我需要先了解更多关于 Android 平台的知识。
标签: java android thread-safety okhttp