Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is multithreading faster than single thread?

I want to check whether multithreading is faster than single thread,then I make a demo here:

public class ThreadSpeedTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("cpu number:"
                + Runtime.getRuntime().availableProcessors());
        singleThreadStart();
//      secondThreadStart();
//      fiveThreadStart();
    }

    private static void sum() {
        long sum = 0;
        for (int i = 0; i < 1000000; i++) {
            sum += i;
        }
        System.out.println(sum);
    }

    private static void singleThreadStart() {
        new Thread(new Runnable() {

            public void run() {
                long start = System.nanoTime();
    //          sum();
    //          sum();
    //          sum();
                sum();
                sum();
                long end = System.nanoTime();
                System.out.println("cost time:" + (end - start));
            }
        }).start();
    }

    private static void secondThreadStart() {
        long start = System.nanoTime();
        Thread thread1 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread1.start();
        Thread thread2 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.nanoTime();
        System.out.println("cost time:" + (end - start));
    }

    private static void fiveThreadStart() {
        long start = System.nanoTime();
        Thread thread1 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread1.start();
        Thread thread2 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread2.start();
        Thread thread3 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread3.start();
        Thread thread4 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread4.start();
        Thread thread5 = new Thread(new Runnable() {

            public void run() {
                sum();
            }
        });
        thread5.start();

        try {
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
            thread5.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.nanoTime();
        System.out.println("cost time:" + (end - start));
    }
}

First I run singleThreadStart with two sum method,the result is

cpu number:4
499999500000
499999500000
cost time:6719000

Then I run secondThreadStart,the result is

cpu number:4
499999500000
499999500000
cost time:14299000

Then I run singleThreadStart with five sum method,the result is

cpu number:4
499999500000
499999500000
499999500000
499999500000
499999500000
cost time:10416000

Finally I run fiveThreadStart,the result is

cpu number:4
499999500000
499999500000
499999500000
499999500000
499999500000
cost time:15708000

My questions are:

  1. SecondThreadStart cost more time than singleThreadStart, is it because the cost of creating thread?
  2. The cpu number is 4, despite the cost of creating thread, so would using more than 4 thread be slower than using four threads?
  3. If I want to do something that takes much more time, is using four threads to do is best?
like image 726
peter_wang Avatar asked Apr 18 '16 03:04

peter_wang


People also ask

Is multithreading always faster than single thread?

Multithreading is always faster than serial. Dispatching a cpu heavy task into multiple threads won't speed up the execution. On the contrary it might degrade overall performance. Imagine it like this: if you have 10 tasks and each takes 10 seconds, serial execution will take 100 seconds in total.

Why is multithreading better than single threading?

Advantages of Multithreaded Processes All the threads of a process share its resources such as memory, data, files etc. A single application can have different threads within the same address space using resource sharing. It is more economical to use threads as they share the process resources.

Is multithreading faster on a single core?

In fact, you should expect the program to run significantly slower than the single-threaded version. Multithreading generally makes programs run slower, not faster.

Is it better to run one thread or multithread on one task?

So when processing a task in a thread is trivial, the cost of creating a thread will create more overhead than distributing the task. This is one case where a single thread will be faster than multithreading.


2 Answers

1.SecondThreadStart cost more time than singleThreadStart, is it because the cost of creating thread?

Certainly there is overhead with creation of thread.

2.The cpu number is 4, despite the cost of creating thread, so using thread number more than 4 will slower than using four threads?

If the threads are finishing very quickly ( Not IO bound and CPU bound), you can have good results even if number of threads are more than number of CPU cores.

3.If I want to do something cost much time, using four threads to do is best?

You can use advanced java concurrent classes ( newWorkStealingPool of Executors)

Refer to this SE question:

Java's Fork/Join vs ExecutorService - when to use which?

In General:

Multi threading may improve throughput of the application by using more CPU power.

it depends on a lot of factors.

  1. Number of threads
  2. CPU cores
  3. Thread creation cost and context switching ( may work against multi-threading)
  4. Data structures
  5. Mutability of data ( may work against multi-threading)
  6. Shared access/ Concurrency of data structure ( may work against multi-threading)
  7. Type of application : CPU bound or IO Bound

Multi threading will provide excellent results if your application is

  1. Less CPU bound, less IO Bound ( But still multi-threading can be used for these applications)

  2. No shared data

If not, the performance depends on above factors and throughput will vary between single threaded application and multi-threading application.

Some good SE questions:

https://softwareengineering.stackexchange.com/questions/97615/what-can-multiple-threads-do-that-a-single-thread-cannot

Does multithreading always yield better performance than single threading?

Why single thread is faster than multithreading in Java?

Good articles:

thetechsolo.wordpress.com article

java-performance article

like image 171
Ravindra babu Avatar answered Oct 31 '22 16:10

Ravindra babu


  1. There is absolutely a cost to creating additional threads. You should have a non-trivial amount of work needed before spinning up a new thread.
  2. I assume this means you have a quad-core CPU. The optimal number of threads actually depends on the workload, if threads are waiting for whatever reason they may be able to context switch to a another thread and you may see a benefit with a number of threads greater than the number of physical cores.
  3. I don't understand the question.
like image 35
Boo Radley Avatar answered Oct 31 '22 17:10

Boo Radley