简体   繁体   English

创建、启动和管理长时间运行的线程的最简洁的方法是什么?

[英]What is the cleanest way to create, start, and manage long-running threads?

Threads add a lot of verbal to the code and make it harder to understand and reason about.线程在代码中添加了很多语言,使其更难理解和推理。 Look at this code for example:例如看这段代码:

public class ConnectionListener implements Runnable {
            
    private Thread thread;
    private boolean running;
    
    public void start() {
        if (!running) {
            thread = new Thread(this);
            thread.start();
        }
    }
    
    public void stop() {
        if (running) {
            running = false;
            thread.interrupt();
        }
    }
    
    @Override
    public void run() {
        running = true;
        
        while (running) {
            // Do some crap
        }
    }
    
}

The whole concern of this class should be listening for connection requests from the network.这个 class 的全部关注点应该是监听来自网络的连接请求。 But look how many lines of code are added just for managing a thread.但是看看添加了多少行代码只是为了管理一个线程。 Is there any way to make this code cleaner?!有没有办法让这段代码更干净?! I don't want to see the thread = new Thread();我不想看到thread = new Thread(); , not the thread variable and not any of the stop() / start() methods! ,不是线程变量,也不是任何stop() / start()方法!

Of course I know what the ExecutorService is... But what if I want to manage a long-running thread?我当然知道ExecutorService是什么……但是如果我想管理一个长时间运行的线程怎么办? By long-running thread, I mean a thread with a life cycle long as the application's life cycle.所谓长时间运行的线程,我的意思是生命周期与应用程序的生命周期一样长的线程。

Do you have any good solution for me?你对我有什么好的解决方案吗? A way to remove the thread creation and management concerns from a class without making the class extend another class?一种从 class 中消除线程创建和管理问题而不使 class 扩展另一个 class 的方法?

I solved the problem by using a single-threaded executor service.我通过使用单线程执行器服务解决了这个问题。 I've also read about the performance differences between Plain Thread , ThreadPool and SingleThreadExecutor - SingleThreadExecutor VS plain thread .我还阅读了Plain ThreadThreadPoolSingleThreadExecutor - SingleThreadExecutor VS plain thread之间的性能差异。

Using a single thread executor allows me to start a single thread and manage it using its Future .使用单线程执行器允许我启动一个线程并使用它的Future管理它。 See code example:见代码示例:

public void func(String[] args) {
   ExecutorService es = Executors.newSingleThreadExecutor();
   Future<?> f = es.submit(Some Runnable);
}

Thanks to @BasilBourque that gave me this solution in the comments.感谢@BasilBourque 在评论中给了我这个解决方案。

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

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