多线程java优化

在我的程序中,我尝试掌握如何使用 ExecutorService 来优化我的程序。出于某种原因,它在两个 Url 上有点卡住了。该http://sjsu.edu/和https://paypal.com。当它坐在这两个上时,它不会继续执行其他 URL。


即使两个域的响应速度不够快,其他 3 个可用线程是否应该不继续?


这是如何以最佳方式修复的?


public class SequentialPinger {

    public static void main(String args[]) throws Exception {


        String[] hostList = {"http://crunchify.com", "http://yahoo.com",

            "http://www.ebay.com", "http://google.com",

            "http://www.example.co", "https://paypal.com",

            "http://bing.com/", "http://techcrunch.com/",

            "http://mashable.com/", "http://thenextweb.com/",

            "http://wordpress.com/", "http://cphbusiness.dk/",

            "http://example.com/", "http://sjsu.edu/",

            "http://ebay.co.uk/", "http://google.co.uk/",

            "http://www.wikipedia.org/",

            "http://dr.dk", "http://pol.dk", "https://www.google.dk",

            "http://phoronix.com", "http://www.webupd8.org/",

            "https://studypoint-plaul.rhcloud.com/", "http://stackoverflow.com",

            "http://docs.oracle.com", "https://fronter.com",

            "http://imgur.com/", "http://www.imagemagick.org"

        };


        List<CallableImpl> callList = new ArrayList();

        ExecutorService es = Executors.newFixedThreadPool(4);


        for (String url : hostList) {

            CallableImpl callable = new CallableImpl(url);

            callList.add(callable);

        }

        for (CallableImpl callableImpl : callList) {

            System.out.println("Trying to connect to: " + callableImpl.getUrl());

            Future<String> lol = es.submit(callableImpl);

            System.out.println("status: " + lol.get());

        }


        es.shutdown();


    }

}

我的 Callable 实现


public class CallableImpl implements Callable<String> {


    private final String url;


    public CallableImpl(String url) {

        this.url = url;

    }


    public String getUrl() {

        return url;

    }


互换的青春
浏览 141回答 3
3回答

心有法竹

在你的代码提交Callable到ExecutorService由一个一个,马上招呼Future.get(),这将阻止,直到结果准备好(或异常是在运行时抛出)。你最好ExecutorService用CompletionSerivce它来包装,一旦它们准备好就提供结果。并将 for 循环拆分为两个循环:一个提交所有Callables,第二个检查结果。ExecutorService es = Executors.newFixedThreadPool(4);ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(es);for (CallableImpl callableImpl : callList) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Trying to connect to: " + callableImpl.getUrl());&nbsp; &nbsp; &nbsp; &nbsp; completionService.submit(callableImpl);}for (int i = 0; i < callList.size(); ++i) {&nbsp; &nbsp; completionService.take().get();&nbsp; &nbsp;//fetch next finished Future and check its result}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java