简体   繁体   English

我应该将 Thread and.join 还是 Callable 与 Future and.get 一起使用?

[英]Should I use Thread and .join or Callable along with Future and .get?

I am writing a simple thread that simply run a process and reads the InputStream .我正在编写一个简单的线程,它只运行一个进程并读取InputStream While reading the input, if it finds a certain string it sets a boolean to true.在读取输入时,如果它找到某个字符串,它会将布尔值设置为 true。 Then when I need to check that boolean I usually do this:然后,当我需要检查那个布尔值时,我通常会这样做:

thread.start();
//some other code
thread.join();
thread.getBoolean();

Or should I instead use Callable along with Future ?还是我应该将CallableFuture一起使用? If so, the correct use would be like this?如果是这样,正确的用法应该是这样的?

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();

In my opinion, it is much better to use interfaces for asynchronous events like this.在我看来,像这样对异步事件使用接口要好得多。 It is clean, faster and reliable.它干净、快速且可靠。
Instead of a bare thread class, we would implement a string processor class that has a listener interface, and a process method that would take the stream and as well as the string to look for within the stream.我们将实现一个字符串处理器类,而不是一个裸线程类,它具有一个侦听器接口,以及一个process方法,该方法将获取流以及要在流中查找的字符串。 So the approximate implementatin would be as following:所以大致的实现如下:

StringProcessor.java字符串处理器.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);
            }
        });
    }
}

We would make use of this class from a superior class like following:我们将使用来自高级类的此类,如下所示:

YourMainOrSuperiorClass.java 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...
    }

}

As you can see, no need to block any thread using async interface patterns.如您所见,无需使用异步接口模式阻塞任何线程。 When you invoke the StringProcessor.process() method, it will process the string within its internal thread without blocking the main thread, and you don't have to wait it to finish, on the contrary you can process more code meanwhile.当您调用StringProcessor.process()方法时,它会在其内部线程中处理字符串,而不会阻塞主线程,您不必等待它完成,相反您可以同时处理更多代码。
In the meantime, the StringProcessor will call the listener's onStringProcessingFinish() method as soon as the result is available and it will handled asynchronously from main thread while the main thread is taking care of something else.同时, StringProcessor将在结果可用时立即调用侦听器的onStringProcessingFinish()方法,并且它将在主线程处理其他事情时从主线程异步处理。

Note that main thread should not return until the result is delivered in case of you need to update some UI elements or something else in the main thread.请注意,如果您需要更新主线程中的某些 UI 元素或其他内容,则主线程不应在结果交付之前返回。 If this is the case you can manage it using a boolean flag, when main thread has been executed all of its stuff then enters to a busy waiting using that flag until the result is delivered.如果是这种情况,您可以使用布尔标志来管理它,当主线程已执行其所有内容时,然后使用该标志进入忙等待状态,直到交付结果。 Once the result has delivered you can set that boolean flag accordingly then.交付结果后,您可以相应地设置该布尔标志。 It is like some kind of using the thread blocking method stuff.这就像某种使用线程阻塞方法的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM