我在 Otherclass 类中有方法 test(),它返回字符串结果:
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;
}
}
我从主类
调用此方法Otherclass oc = new Otherclass();
System.out.println(oc.test());
并希望获得结果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
请帮助,运行Thread后,我可以通过哪些方法获得 test()方法的结果?
答案 0 :(得分:5)
您需要使用t
join()
主题完成
t.start();
t.join(); // this makes the main thread wait for t to finish
String result = "result value i = "+i;
如果需要从线程返回值,请考虑实现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());
}
输出是:
value 1
value 2
value 3
value 4
value 5
value 6
value 7
value 8
value 9
value 10
10
答案 1 :(得分:2)
尝试在t.start()之后添加t.join()。这将使主线程等到线程2结束
答案 2 :(得分:0)
我同意上述答案。您还可以将回调接口传递给测试函数并以此方式处理值。
interface Callback {
public void onValueChanged(String value);
}
public void Test(Callback callback){
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(i < 10){
callback.onValueChanged("Value = " + i);
i++;
}
}
});
t.start();
}
// Now print the values live from calling the method
Test(new Callback(){
@Override
public void onValueChanged(String value){
System.out.println(value);
}
});