多线程比单线程更快吗? [英] Is multithreading faster than single thread?

查看:180
本文介绍了多线程比单线程更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查多线程是否比单线程更快,然后我在这里进行演示:

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

首先我用两个sum方法运行singleThreadStart,结果是

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

cpu number:4
499999500000
499999500000
cost time:6719000

然后我运行secondThreadStart,结果是

Then I run secondThreadStart,the result is

cpu number:4
499999500000
499999500000
cost time:14299000

然后我使用五个sum方法运行singleThreadStart,结果是

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

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

最后我运行fiveThreadStart,结果是

Finally I run fiveThreadStart,the result is

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

我的问题是:

1.SecondThreadStart比singleThreadStart花费更多时间,是我t因为创建线程的成本?

2.尽管创建线程的成本,cpu数是4,那么使用超过4个线程会比使用4个线程慢吗?

3.如果我想做一些花费更多时间的事情,最好使用四个线程吗?

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?

推荐答案


1.SecondThreadStart花费的时间比singleThreadStart多,是不是因为创建线程的成本?

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

当然有创建线程的开销。

Certainly there is overhead with creation of thread.


2.尽管创建线程的成本很高,但cpu编号是4,所以使用超过4的线程数会比使用四个线程慢吗?

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?

如果线程很快完成(没有IO绑定和CPU绑定),你可以有好处结果即使线程数超过CPU核心数。

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.如果我想做一些花费很多时间的东西,使用fou r线程要做的最好?

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

你可以使用高级java并发类( newWorkStealingPool 执行者

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

请参阅此SE问题:

Java的Fork / Join vs ExecutorService - 何时使用?

一般情况:

多线程可以提高吞吐量通过使用更多CPU功率来应用。

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

这取决于很多因素。


  1. 线程数

  2. CPU核心

  3. 线程创建成本和上下文切换(可能对多线程起作用)

  4. 数据结构

  5. 数据的可变性(可能对多线程有效)

  6. 共享访问/数据结构的并发(可能会起作用)多线程)

  7. 应用程序类型:CPU绑定或IO绑定

  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

如果您的应用程序是


  1. 更少的CPU限制,更少的IO绑定(但仍然可以使用多线程这些应用程序)

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

没有共享数据

如果没有,性能取决于上述因素,单线程应用程序和多线程之间的吞吐量会有所不同线程应用程序。

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

一些好的SE问题:

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

多线程总是比单线程产生更好的性能吗?

为什么单线程比Java中的多线程更快?

好文章:

thetechsolo.wordpress.com 文章

java-performance 文章

这篇关于多线程比单线程更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆