Wer*_*der 1 java multithreading android
我在Otherclass类中有方法test(),它返回String结果:
public class Otherclass {
int i = 0;
public String test()
{
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("GoToThread");
while(i < 10) {
i++;
System.out.println("value "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
String result = "result value i = "+i;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
我从主类调用此方法
Otherclass oc = new Otherclass();
System.out.println(oc.test());
Run Code Online (Sandbox Code Playgroud)
并希望得到结果为result value i = 10
但是在返回methos结果后运行Otherclass中的线程,我得到的结果如下:
result value i = 0
GoToThread
value1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10
Run Code Online (Sandbox Code Playgroud)
请帮忙,运行Thread后我可以通过哪些方法获得test()方法的结果?
你需要等待你的t线程完成使用join():
t.start();
t.join(); // this makes the main thread wait for t to finish
String result = "result value i = "+i;
Run Code Online (Sandbox Code Playgroud)
Callable如果需要从线程返回值,请考虑实现.例如:
public static void main(String[] args) throws Exception {
Callable<Integer> worker = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
Integer i = 0;
while (i < 10) {
i++;
System.out.println("value " + i);
Thread.sleep(500);
}
return i;
}
};
Future<Integer> result = Executors.newSingleThreadExecutor().submit(worker);
System.out.println(result.get());
}
Run Code Online (Sandbox Code Playgroud)
输出是:
value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10
10
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
617 次 |
| 最近记录: |