我有2个处理程序,第一个处理程序获取IP,第二个尝试获取国家/地区代码。如果我知道IP,我可以执行第二个处理程序,则第二个是依赖的。 但是,当我执行我的代码时,两个线程同时执行,我尝试使用myThread.join,但是行为却相同。
public class SplashScreen extends AppCompatActivity{
Handler handler = new Handler();
SharedPreferences settings;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
settings = this.getSharedPreferences("appInfo", 0);
String ipAddress = settings.getString("ipAddress", null);
if(ipAddress == null) {
Runnable runnable = new IPAddressThread(handler, this);
handler.postDelayed(runnable, 5000);
Thread thread = new Thread(runnable);
thread.start();
}
String countryCode = settings.getString("countryCode", null);
String storeNumber = settings.getString("storeNumber", null);
if(countryCode == null || storeNumber == null) {
Handler handlerStore= new Handler();
Runnable runnableStore = new StoreDetailThread(handlerStore, this);
handlerStore.postDelayed(runnableStore, 5000);
Thread threadStore = new Thread(runnableStore);
threadStore.start();
} }
和可运行的实现:
public class IPAddressThread implements Runnable {
private Handler handler;
private SplashScreen settings;
IPAddressThread(Handler handler, SplashScreen settings){
this.handler=handler;
this.settings=settings;
}
/**
*
*/
@Override
public void run() {
handler.postDelayed(this, 5000);
String ip= NetworkDetails.getInstance().getIpAddress();
if(ip!=null && !ip.isEmpty()){
settings.setStoreFormat("ipAddress", ip);
handler.removeCallbacks(this);
}else{
System.out.println("Searching....");
}
}
public class StoreDetailThread implements Runnable{
private Handler handler;
private SplashScreen settings;
private String storeDetail;
/**
* Class Constructor.
*
* @param handler
* @param settings
*/
public StoreDetailThread(Handler handler, SplashScreen settings){
this.handler=handler;
this.settings=settings;
}
/**
*
*/
@Override
public void run() {
String host= NetworkDetails.getInstance().getHostNetwork();
if(host.contains(PATTERN_FOR_STORE_NUMBER)) {
try{
String countryCode=storeDetail.substring(FIRST_POSITION_COUNTRY_CODE,LAST_POSITION_COUNTRY_CODE);
String storeNumber=storeDetail.substring(FIRST_POSITION_STORE_NUMBER,LAST_POSITION_STORE_NUMBER);
settings.setStoreFormat("countryCode", countryCode);
settings.setStoreFormat("storeNumber", storeNumber);
handler.removeCallbacks(this);
}catch (IndexOutOfBoundsException exception){
handler.postDelayed(this, 5000);
}
}else{
handler.postDelayed(this, 5000);
}
}
}
当第一个线程完成时如何调用第二个线程?