我是线程新手。问题是:这是从异步Retrofit线程中提取值的正确方法吗?为什么不让“0代码退出”?
这是主要代码
import com.google.gson.GsonBuilder;
import iceandfire.Callbacks.RootCallback;
import iceandfire.Models.Root;
import iceandfire.Utils.IceFireClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Main implements RootCallback
{
public static void main(String [] args)
{
RequestRoot(new Main());
//this imitates UI thread
Thread thread = new Thread()
{
public void run()
{
int counter = 5;
while (counter >= 0)
{
System.out.println("I am not retrofit Call");
counter -= 1;
try
{
Thread.sleep(1000); // 1 second
} catch (Exception e)
{
e.printStackTrace();
}
}
}
};
thread.start();
}
public static void RequestRoot(final RootCallback rootCallback)
{
Retrofit.Builder retroBuilder = new Retrofit.Builder()
.baseUrl("https://anapioficeandfire.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = retroBuilder.build();
IceFireClient client = retrofit.create(IceFireClient.class);
Call<Root> kall = client.root();
kall.enqueue(new Callback<Root>()
{
@Override
public void onResponse(Call<Root> call, Response<Root> response)
{
Root bloodyRoot = response.body();
rootCallback.onSuccess(bloodyRoot);
}
@Override
public void onFailure(Call<Root> call, Throwable t)
{
}
});
}
@Override
public void onSuccess(Root bloodyRoot)
{
System.out.println( new GsonBuilder().setPrettyPrinting().create().toJson(bloodyRoot).toString());
}
}
回调
package iceandfire.Callbacks;
import iceandfire.Models.Root;
public interface RootCallback
{
void onSuccess(Root bloodyRoot);
}
我期望的是:5x消息“我不是Retrofit call”; Json是我在之前,之后或之前的消息之间的任何随机时间从iceandfireapi/root获得的。并且最后但并非最不重要的一切结束:“进程以退出代码0结束”
但我得到的是无限循环:5x消息,Json和NO退出消息。
P.S。计时器线程用于“模仿”一些UI事物。虽然改造正在提出要求。