简体   繁体   English

具有四核处理器的笔记本电脑中的Java多线程

[英]Java multithreading in a laptop having quad-core processor

I was going through a Java tutorial where it was mentioned that actual multithreading doesn't happen in a machine having a single processor. 我正在阅读Java教程,其中提到在具有单个处理器的机器中不会发生实际的多线程。 It mentioned that OS allots a specified amount of time for the Java process and JVM thread scheduler picks up threads for running one thread at a time for a small amount of time. 它提到操作系统为Java进程分配指定的时间,JVM线程调度程序选择一次运行一个线程的线程,持续时间很短。

I have a laptop which quadcore processor - it is possible to run a multi-threaded program faster programatically by running one thread in each core? 我有一台四核处理器的笔记本电脑 - 通过在每个核心运行一个线程,可以以编程方式更快地运行多线程程序吗? The reason why I am asking this question is because the book mentioned that only a true multi processor system can do multiple things at the same time. 我问这个问题的原因是因为书中提到只有真正的多处理器系统才能同时做多件事。

Even a single CPU can do "multiple things at the same time" in a loose sense, but they are not truly in parallel. 即使是单个CPU也可以在宽松的意义上同时执行“多个事物”,但它们并非真正并行。 You can start 100 threads to run on a single core and they will get time slices during which each of them can run a few instructions, thus creating the impression that they are all executing at the same time. 您可以启动100个线程在单个核心上运行,并且它们将获得时间片,在此期间每个线程可以运行一些指令,从而产生它们全部同时执行的印象。

As I've said in another SO post: multithreading on dual core machine? 正如我在另一篇SO帖子中所说: 双核机器上的多线程?

The term threads usually covers three abstraction layers: 术语线程通常包含三个抽象层:

  1. User threads are threads launched by applications and are mapped N:M to: 用户线程是应用程序启动的线程,并将N:M映射到:
  2. Kernel threads , which are threads managed by the operating system, mapped N:M to: 内核线程是由操作系统管理的线程 ,将N:M映射到:
  3. Hardware threads , which are the actual physical resources available. 硬件线程 ,它们是可用的实际物理资源。

Java threads are user threads. Java线程是用户线程。 The 4 cores in your CPU count as hardware threads. CPU中的4个内核计为硬件线程。 Since the mapping is N:M across the layers, you can see that you can have several user threads mapped to a smaller number of hardware threads. 由于跨层的映射是N:M,您可以看到可以将多个用户线程映射到较少数量的硬件线程。

Now, having said this, there are generally two classes of thread activities, each with their own quirks: 现在,说了这个,通常有两类线程活动,每个都有自己的怪癖:

  1. I/O threads : these threads spend most of their time waiting on read/write operations from a stream and are blocked in the meantime (they are not scheduled for execution until an event occurs to wake them up). I / O线程 :这些线程大部分时间都在等待来自流的读/写操作,并在此期间被阻塞(它们不会被调度执行,直到事件发生才唤醒它们)。 There are light on the CPU and a lot of them can run concurrently even on a single core. CPU上有亮点,即使在单核上也可以同时运行。
  2. Computational threads : these thread do a lot of number crunching and use the CPU to the maximum. 计算线程 :这些线程执行大量数字运算并最大限度地使用CPU。 Generally starting more than (2x the number of available cores) such threads is going to degrade performance, because the CPU has a limited number of functional units: ALUs, FPUs, etc. 通常启动超过(可用内核数量的2倍)这样的线程会降低性能,因为CPU具有有限数量的功能单元:ALU,FPU等。

The second class of threads above lets you really see the benefit or running a multithreaded java program on your quad-core CPU. 上面的第二类线程让您可以在四核CPU上真正看到好处或运行多线程Java程序。 Here is a simple example of a program that executes squaring of 1.000.000.000 numbers first sequentially and then in parallel using a thread pool with 4 threads: 下面是一个程序的简单示例,该程序首先按顺序执行1.000.000.000个数字的平方,然后使用4个线程的线程池并行执行:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class ThreadTask implements Runnable {

    private int total = 0;

    public ThreadTask(int total) {
        this.total = total;
    }

    @Override
    public void run() {
        int value = 0;
        for(int i = 0; i < total; i++) {
            value = i * i;
        }
    }       
}

public class Test {

    public static void main(String[] args) throws InterruptedException {

        int total = 1000000000;

        long start = System.currentTimeMillis();
        long value = 0;
        for(int i = 0; i < total; i++) {
            value = i * i;
        }       
        long stop = System.currentTimeMillis();

        System.out.println((stop - start) + " ms");

        ExecutorService exec = Executors.newFixedThreadPool(4);
        start = System.currentTimeMillis();
        for(int i = 0; i < 4; i++) {
            exec.submit(new ThreadTask(total / 4));
        }
        exec.shutdown();
        exec.awaitTermination(10, TimeUnit.SECONDS);
        stop = System.currentTimeMillis();

        System.out.println((stop - start) + " ms");     
    }
}

Feel free to adjust the value of total if it's running too fast. 随意调整的价值total ,如果它的运行速度太快。 Now I'm working on a netbook with Intel Atom, so it not really fast. 现在我正在使用英特尔凌动的上网本,所以它不是很快。

A multi-core processor can 'truly' parallelize the work in your application up to the number of cores you have. 多核处理器可以“真正”并行化应用程序中的工作,最多可达到您拥有的核心数。 In your case, that would be 4 threads. 在你的情况下,那将是4个线程。 Read more about multi-core vs multi-processor at Wikipedia . 阅读Wikipedia上有关多核与多处理器的更多信息。 Having said that, you can realize performance benefits with a multi-threaded algorithm on a single core CPU, despite the fact that you only have one processor. 话虽如此,您可以在单核CPU上通过多线程算法实现性能优势,尽管您只有一个处理器。

The improvement in performance gained by the use of a multi-core processor depends very much on the software algorithms used and their implementation. 使用多核处理器所带来的性能提升在很大程度上取决于所使用的软件算法及其实现。 In particular, possible gains are limited by the fraction of the software that can be parallelized to run on multiple cores simultaneously; 特别是,可能的增益受到可并行化以同时在多个内核上运行的软件部分的限制; this effect is described by Amdahl's law. Amdahl定律描述了这种效应。 In the best case, so-called embarrassingly parallel problems may realize speedup factors near the number of cores, or even more if the problem is split up enough to fit within each core's cache(s), avoiding use of much slower main system memory. 在最好的情况下,所谓的令人尴尬的并行问题可能会在核心数量附近实现加速因子,如果问题分裂得足以适应每个核心的缓存,则可能会更多,从而避免使用更慢的主系统内存。 Most applications, however, are not accelerated so much unless programmers invest a prohibitive amount of effort in re-factoring the whole problem 2 . 然而,大多数应用程序都没有加速,除非程序员投入大量精力来重新分解整个问题2 The parallelization of software is a significant ongoing topic of research. 软件的并行化是一个重要的研究课题。

Also see this StackOverflow question. 另请参阅此StackOverflow问题。

Even with only one processor multiple threads can make your program faster it all depends on the work you're trying to speed up. 即使只有一个处理器,多个线程也可以使您的程序更快,这一切都取决于您尝试加速的工作。 For instance if your threads are waiting for IO. 例如,如果您的线程正在等待IO。 If it's purely computational then you'd probably want to limit your threads to your number of cores. 如果它纯粹是计算的,那么你可能想要将线程限制为你的核心数量。

Measure it test it with experiments. 测量它用实验测试它。

I can confirm that, on my i3 laptop, algorithms that run in parallel go nearly twice as fast aspects a serial algorithm. 我可以确认,在我的i3笔记本电脑上,并行运行的算法的速度几乎是串行算法的两倍。

more context added below... 下面添加更多上下文...

These are highly computational algorithms with no I/O. 这些是高度计算的算法,没有I / O. Basically, calculating statistics on N large arrays, where each array can be done independently. 基本上,计算N个大型阵列的统计数据,其中每个阵列可以独立完成。 I find that using a thread pool of 2-4 threads all yields about the same speed increase - 2X. 我发现使用2-4个线程的线程池都会产生大约相同的速度增加 - 2倍。 Going to 8 or more threads, things start slowing down slightly as you get more contention (and are using up more memory). 转到8个或更多线程,当你获得更多争用(并且正在消耗更多内存)时,事情开始稍微放缓。 On a processor with more cores these values would change. 在具有更多内核的处理器上,这些值会发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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