简体   繁体   中英

Java - Is this method multithreaded?

First of all, thanks for taking time to read this. The code is written and executed as a JUnit test, so I dont know whether that affects the answer.

@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.
}

No it is not.

new runnableClass().run();

This calls the run method directly as defined above it.

If you want this code to be multithreaded you will need to use:

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

No, the runnable will be executed by the main caller thread, just like this:

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

To make it multi-threaded, you can create new threads and call start() :

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

This method is not multi threaded due to the creation of Runnable instance in your method.

Example to showcase answer:

Code

 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();
        }
    }

Output

main
main
main
main
main
main
main
main
main
main

To make this method multi threaded you could use an ExecutorService.

Code

 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();
}

Output

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

As a complement see this tutorial, it explains well what you want to know. And it has example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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