如何使用MultithreadedTC测试多线程应用程序?

时间:2014-01-01 17:12:26

标签: java multithreading unit-testing testing

我正在努力使用multithreadedTC来测试我的多线程应用程序。该网站提供了一些示例(http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html#examples2to4),但所有示例都针对多线程构造(例如AtomicInteger,Semaphore)进行测试,与使用多线程构造的方法相反。

现在我有一个简单的内容提取器。如何使用multithreadedTC测试“fetch()”方法?

    public class ConcurrentFetcher {

    private URL[] urls = new URL[3];

    public ConcurrentFetcher() throws MalformedURLException {
        urls[0] = new URL("http://www.yahoo.com");
        urls[1] = new URL("http://www.google.com");
        urls[2] = new URL("http://www.bing.com");
    }

    private void fetch() throws InterruptedException, ExecutionException {
        ExecutorService es = Executors.newFixedThreadPool(3);

        List<Callable<String>> tasks = new ArrayList<Callable<String>>();

        for (final URL url : urls) {
            tasks.add(new Callable<String>() {

                @Override
                public String call() throws Exception {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

                    String line;
                    StringBuilder sb = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        sb.append(line);
                    }
                    return sb.toString();
                }
            });
        }

        List<Future<String>> promises = es.invokeAll(tasks, 10000, TimeUnit.SECONDS);

        for (Future promise : promises) {
            System.out.println(promise.get());
        }

        es.shutdown();
    }

    public static void main(
            String[] args) throws IOException, InterruptedException, ExecutionException {

        ConcurrentFetcher fetcher = new ConcurrentFetcher();
        fetcher.fetch();
    }

}

0 个答案:

没有答案