如何在Java中将方法作为后台进程进行调用 [英] How to make calling a Method as a background process in java

查看:181
本文介绍了如何在Java中将方法作为后台进程进行调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,当用户登录时我具有此逻辑,它将调用下面的方法,其中包含用户拥有的所有符号.

public void sendSymbol(String commaDelimitedSymbols) {
        try {
            // further logic
        } catch (Throwable t) {

        }
    }

我的问题是,由于发送符号的任务可以缓慢完成但必须完成,所以无论如何我都可以将其作为后台任务进行?

这可能吗?

请分享您的观点.

解决方案

您正在寻找类似的东西.

    ExecutorService service = Executors.newFixedThreadPool(4);
    service.submit(new Runnable() {
        public void run() {
            sendSymbol();
        }
    });

创建执行程序服务.这将保留线程池以供重用.与每次为每个异步方法调用创建一个新线程相比,效率要高得多.

如果您需要对ExecutorService进行更高程度的控制,请使用 ThreadPoolExecutor .至于配置此服务,将取决于您的用例.您多久调用一次此方法?如果经常,您可能至少要一直在池中保留一个线程.我最多只能保留4个或8个以上.

由于您每半秒只调用一次sendSymbol,因此一个线程应该足够,因为sendSymbols并不是一个非常耗时的例程.我将配置一个带有1个线程的固定线程池.您甚至可以重用此线程池来提交其他异步任务.

只要您提交的内容不太多,当您致电sendSymbol时它就会响应.

In my application , I have this logic when the user logins , it will call the below method , with all the symbols the user owns .

public void sendSymbol(String commaDelimitedSymbols) {
        try {
            // further logic
        } catch (Throwable t) {

        }
    }

my question is that as this task of sending symbols can be completed slowly but must be completed , so is there anyway i can make this as a background task ??

Is this possible ??

please share your views .

解决方案

Something like this is what you're looking for.

    ExecutorService service = Executors.newFixedThreadPool(4);
    service.submit(new Runnable() {
        public void run() {
            sendSymbol();
        }
    });

Create an executor service. This will keep a pool of threads for reuse. Much more efficient than creating a new Thread each time for each asynchronous method call.

If you need a higher degree of control over your ExecutorService, use ThreadPoolExecutor. As far as configuring this service, it will depend on your use case. How often are you calling this method? If very often, you probably want to keep one thread in the pool at all times at least. I wouldn't keep more than 4 or 8 at maximum.

As you are only calling sendSymbol once every half second, one thread should be plenty enough given sendSymbols is not an extremely time consuming routine. I would configure a fixed thread pool with 1 thread. You could even reuse this thread pool to submit other asynchronous tasks.

As long as you don't submit too many, it would be responsive when you call sendSymbol.

这篇关于如何在Java中将方法作为后台进程进行调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆