java - 多线程比单线程快吗?

标签 java multithreading processor

我想看看多线程是否比单线程快,所以我在这里做了一个演示:

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,结果是

cpu number:4
499999500000
499999500000
cost time:6719000

然后我运行secondThreadStart,结果是

cpu number:4
499999500000
499999500000
cost time:14299000

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

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

最后我运行了 fiveThreadStart,结果是

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

我的问题是:

  1. SecondThreadStart 比 singleThreadStart 耗时更多,是否因为创建线程的成本?
  2. CPU 数量为 4,尽管创建线程的成本很高,那么使用 4 个以上的线程会比使用 4 个线程慢吗?
  3. 如果我想做一些需要更多时间的事情,最好使用四个线程吗?

最佳答案

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 using thread number more than 4 will slower than using four threads?

如果线程完成得非常快(不受 IO 限制和 CPU 限制),即使线程数多于 CPU 内核数,您也可以获得良好的结果。

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

您可以使用高级 java 并发类(ExecutorsnewWorkStealingPool)

引用这个SE问题:

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

总的来说:

多线程可以通过使用更多的 CPU 能力来提高应用程序的吞吐量。

这取决于很多因素。

  1. 线程数
  2. CPU 内核
  3. 线程创建成本和上下文切换(可能适用于多线程)
  4. 数据结构
  5. 数据的可变性(可能不利于多线程)
  6. 数据结构的共享访问/并发(可能适用于多线程)
  7. 应用类型:CPU bound 或 IO Bound

如果您的应用程序是多线程将提供出色的结果

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

  2. 没有共享数据

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

一些很好的 SE 问题:

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?

好文章:

thetechsolo.wordpress.com文章

java-performance文章

关于java - 多线程比单线程快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36684832/

相关文章:

java - 如何释放 Activity 完成的线程?

c++ - 全局变量的线程和函数调用安全

python - python 中应该如何生成线程

java - 在java中通过静态方法访问私有(private)变量

java - 增加 createCompoundBorder 的厚度

java - 使用 Java 反射类获取方法

c# - 处理器的特性C#

c - 多线程查找整数的质因数,段错误

java - java是否提供了一个干净的机制来确保线程关闭逻辑在线程死亡时运行?

c# - 检索物理核心处理器的数量