【发布时间】:2019-06-01 05:36:24
【问题描述】:
我创建了这个小项目来展示我想要做什么,但实际上它将用于使用大约 60 个不同线程的大型应用程序中。
我有两节课
public class Main {
public static void main(String[] args) {
Http http = new Http();
Thread threadHttp = new Thread(http, "httpThread1");
threadHttp.start();
http.getPage("http://google.com"); // <-- This gets called on
// the main thread,
//I want it to get called from the
// "httpThread1" thread
}
}
和
public class Http implements Runnable {
volatile OkHttpClient client;
@Override
public void run() {
client = new OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS).retryOnConnectionFailure(true).build();
}
public void getPage(String url) {
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}
我希望能够从主线程调用getPage 方法,但让它在我们启动和初始化的httpThread1 上执行OkHttpClient client
这可能吗?怎么办?
【问题讨论】:
-
updater.test(someVar)有什么问题? -
updater.test? -
不会在主线程上测试运行吗?不是我为更新程序启动的新线程?
-
@Arya 你的最后一句话是
How can I call test from the main thread ... -
@Arya 有点不清楚。为什么不将
var传递给构造函数并从run()方法中调用test的方式与传递new Date()的方式相同?如果var值只有在threadUpdater启动后才被主线程知道,那么您可能想要使用回调之类的东西...
标签: java multithreading