![](/img/trans.png)
[英]Can't use the get mothod on my Future parameter to get result of thread with the callable interface
[英]Should I use Thread and .join or Callable along with Future and .get?
我正在编写一个简单的线程,它只运行一个进程并读取InputStream
。 在读取输入时,如果它找到某个字符串,它会将布尔值设置为 true。 然后,当我需要检查那个布尔值时,我通常会这样做:
thread.start();
//some other code
thread.join();
thread.getBoolean();
还是我应该将Callable
与Future
一起使用? 如果是这样,正确的用法应该是这样的?
Callable<Boolean> myTask = new Task();
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Boolean> future = executorService.submit(myTask);
//some other code
Boolean output = future.get();
System.out.println(output);
executorService.awaitTermination(3, TimeUnit.SECONDS);
executorService.shutdownNow();
在我看来,像这样对异步事件使用接口要好得多。 它干净、快速且可靠。
我们将实现一个字符串处理器类,而不是一个裸线程类,它具有一个侦听器接口,以及一个process
方法,该方法将获取流以及要在流中查找的字符串。 所以大致的实现如下:
字符串处理器.java
class StringProcessor {
public interface StringProcessorListener {
void onStringProcessingFinish(boolean found);
}
private ExecutorService executorService = Executors.newSingleThreadExecutor();
private StringProcessorListener listener;
public StringProcessor(StringProcessorListener listener) {
this.listener = listener;
}
public void process(InputStream inputStream, String strToFind) {
executorService.execute(()-> {
// Do the processing here...
while(inputStream.availlable() > 0) {
// Processing... maybe some string building or something else...
// Processing code goes here...
// A string built check it out
if(str.equals(strToFind)) {
// The string what we look for is found, notify the listener with true
listener.onStringProcessingFinish(true);
return;
}
// If reached here then the string not found, notify with false
listener.onStringProcessingFinish(false);
}
});
}
}
我们将使用来自高级类的此类,如下所示:
YourMainOrSuperiorClass.java
class YourMainOrSuperiorClass {
public static void main(String[] args) {
// Insantiate or get an input stream from where you wish...
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
// Search a string using the processor class
new StringProcessor(new StringProcessorListener {
@Override
public void onStringProcessingFinish(boolean found) {
if(found) {
// The string has been found, handle it
}
else {
// The String has not been found, handle it
}
}
})
.process(bufferedInputStream, "String to find");
// Maybe some more stuff to process from here...
}
}
如您所见,无需使用异步接口模式阻塞任何线程。 当您调用StringProcessor.process()
方法时,它会在其内部线程中处理字符串,而不会阻塞主线程,您不必等待它完成,相反您可以同时处理更多代码。
同时, StringProcessor
将在结果可用时立即调用侦听器的onStringProcessingFinish()
方法,并且它将在主线程处理其他事情时从主线程异步处理。
请注意,如果您需要更新主线程中的某些 UI 元素或其他内容,则主线程不应在结果交付之前返回。 如果是这种情况,您可以使用布尔标志来管理它,当主线程已执行其所有内容时,然后使用该标志进入忙等待状态,直到交付结果。 交付结果后,您可以相应地设置该布尔标志。 这就像某种使用线程阻塞方法的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.