【原创】Thread.yield阻塞判断超时返回值的实践
public class Test {
class HttpUtils {
private String json;
public String http(String url) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
json = extracted();
} catch (Exception e) {
e.printStackTrace();
json = "Fail";
} finally {
System.out.println("============= finally -> 关闭连接!");
}
}
});
thread.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
int count = 2;
while (count-- > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
json = "Thread Return";
}
});
thread2.start();
while (json == null || json.equals("")) {
Thread.yield();
}
if (thread != null) {
thread.stop();
}
if (thread2 != null) {
thread2.stop();
}
return json;
}
private String extracted() {
int i = 0;
while (++i < 2) {
System.out.println(i + "业务处理中...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "OK";
}
}
public static void main(String[] args) {
String json = new Test().new HttpUtils().http("url");
System.out.println("@@@@@@@@@ 返回值:" + json);
}
}

转载请注明:文章转载自:桐星豆 [https://txdou.com]
本文标题:【原创】Thread.yield阻塞判断超时返回值的实践
本文地址:http://txdou.com/article116


- 注意:“桐星豆”只会以“回复”的身份出现,不会以“咨询”的身份出现在留言或评论中,凡是以“咨询”的身份出现的留言或评论均为他人盗用!
- 本站用以回复网友评论的唯一名称是“桐星豆”,除此外均无效,网友不得用此名进行相应文章的评论或回复!
- 用户言论只代表其个人观点,不代表桐星豆的观点或立场!
- 非诚勿扰,请友好如实的评论,杜绝谩骂、人格攻击等一切伤人言论,请严格遵循中华人民共和国法律法规!
- 桐星豆拥有最终解释权,如有网友违规,本站将有权删除或屏蔽违规评论,情节严重者账户加入黑名单、永久封IP并报司法部门严惩!
- 您一旦参与评论本站则默认为您已经同意以上条款,否则“非诚勿扰”,谢谢合作!