Java - 这种方法是多线程的吗?

时间:2018-04-19 14:09:36

标签: java multithreading junit parallel-processing

首先,感谢您花时间阅读本文。代码是作为JUnit测试编写和执行的,所以我不知道这是否会影响答案。

@Test
public void generate___() {
    long startTime = System.nanoTime();
    for (File file : getResultsFromFolder("C:\\temp\\....")) {
        class runnableClass implements Runnable{
            public void run() {
                // do something with file

            }
        }
        new runnableClass().run();
    }

    long endTime = System.nanoTime();
    System.out.println("total took: " + (endTime - startTime) / 1000000); //divide by 1000000 to get milliseconds.
}

4 个答案:

答案 0 :(得分:2)

不,runnable将由主调用者线程执行,就像这样:

for (File file : getResultsFromFolder("C:\\temp\\....")) {
     // do something with file
}

要使其成为多线程,您可以创建新线程并调用start()

for (final File file : getResultsFromFolder("C:\\temp\\....")) {
    class runnableClass implements Runnable{
        public void run() {
            // do something with file
        }
    }
    new Thread(new runnableClass()).start();
}

答案 1 :(得分:2)

由于在方法中创建了Runnable实例,因此该方法不是多线程的。

展示答案的示例:

<强> 代码

 public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            };
            myRunnable.run();
        }
    }

<强> 输出

main
main
main
main
main
main
main
main
main
main

要使此方法成为多线程,您可以使用ExecutorService。

<强> 代码

 public static void main(String[] args) {

    ExecutorService executorService = Executors.newFixedThreadPool(2);

    for (int i = 0; i < 10; i++) {
        Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        };

        executorService.execute(myRunnable);
    }

    executorService.shutdown();
}

<强> 输出

pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2

答案 2 :(得分:1)

不,不是。

new runnableClass().run();

这直接按照上面的定义调用run方法。

如果您希望此代码为多线程,则需要使用:

new Thread(new runnableClass()).start();

答案 3 :(得分:0)

作为补充参见本教程,它很好地解释了您想要了解的内容。 它有例子

https://www.tutorialspoint.com/java/java_multithreading.htm