Thread.join()--Java实现主线程等待子线程

Thread.join(),是用来指定当前主线程等待其他线程执行完毕后,再来继续执行Thread.join()后面的代码

String string = null;

Thread thread = new Thread(){
            public void run() {
try {
  string = query(username, pwd);
} catch (Exception e) {
e.printStackTrace();
}
   };
};
thread.start();
thread.join();

if (string .equals("admin") )
{
return true;
}

上边一段代码用于登录验证,query用于向服务器查询数据,费时操作不能放到主线程,而新开子线程后用于判断的if代码段在子线程结束前就执行了,起不到判断效果,因此使用用join函数,这样就可以等待子线程执行完再执行判断。

join函数可参考http://blog.csdn.net/JustForFly/article/details/41118265

猜你喜欢

转载自blog.csdn.net/huazicomeon/article/details/58656552