Java 是否支持多核处理器/并行处理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3330430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:14:56  来源:igfitidea点击:

Does Java have support for multicore processors/parallel processing?

javamultithreadingparallel-processingmulticore

提问by Rafe Kettler

I know that now that most processors have two or more cores, multicore programming is all the rage. Is there functionality to utilize this in Java? I know that Java has a Thread class, but I also know this was around a long time before multicores became popular. If I can make use of multiple cores in Java, what class/technique would I use?

我知道现在大多数处理器都有两个或更多内核,多核编程风靡一时。是否有在 Java 中使用它的功能?我知道 Java 有一个 Thread 类,但我也知道这是在多核流行之前的很长一段时间。如果我可以在 Java 中使用多个内核,我会使用什么类/技术?

采纳答案by bakkal

Does Java have support for multicore processors/parallel processing?

Java 是否支持多核处理器/并行处理?

Yes. It also has been a platform for other programming languages where the implementation added a "true multithreading" or "real threading" selling point. The G1 Garbage Collectorintroduced in newer releases also makes use of multi-core hardware.

是的。它也是其他编程语言的平台,其中的实现增加了“真正的多线程”或“真正的线程”卖点。新版本中引入的G1 垃圾收集器也使用了多核硬件。

Java Concurrency in Practice

Java 并发实践

Try to get a copy of the Java Concurrency in Practicebook.

尝试获取Java 并发实践手册的副本。



If I can make use of multiple cores in Java, what class/technique would I use?

如果我可以在 Java 中使用多个内核,我会使用什么类/技术?

java.util.concurrent

java.util.concurrent

Utility classescommonly useful in concurrent programming. This package includes a few small standardized extensible frameworks, as well as some classes that provide useful functionality and are otherwise tedious or difficult to implement. Here are brief descriptions of the main components.

实用程序类通常用于 并发编程。这个包包括一些小的标准化的可扩展框架,以及一些提供有用功能的类,否则很乏味或难以实现。以下是主要组件的简要说明。

Executors

执行者

Executoris a simple standardized interface for defining custom thread-like subsystems, including thread pools, asynchronous IO, and lightweight task frameworks.

Executor是一个简单的标准化接口,用于定义自定义的类线程子系统,包括线程池、异步 IO 和轻量级任务框架。

Queues

队列

The java.util.concurrent ConcurrentLinkedQueueclass supplies an efficient scalable thread-safe non-blocking FIFO queue.

java.util.concurrentConcurrentLinkedQueue类提供了一个高效的可扩展线程安全非阻塞 FIFO 队列。

Timing

定时

The TimeUnitclass provides multiple granularities (including nanoseconds) for specifying and controlling time-out based operations. Most classes in the package contain operations based on time-outs in addition to indefinite waits.

TimeUnit类提供了用于指定和控制超时基于操作的多个粒度(包括毫微秒)。除了无限期等待之外,包中的大多数类都包含基于超时的操作。

Synchronizers

同步器

Four classes aid common special-purpose synchronization idioms. Semaphoreis a classic concurrency tool. CountDownLatchis a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold. [...]

四个类有助于通用的专用同步习语。Semaphore是一个经典的并发工具。CountDownLatch是一个非常简单但非常常见的实用程序,用于阻塞直到给定数量的信号、事件或条件成立。[...]

Concurrent Collections

并发集合

Besides Queues, this package supplies a few Collection implementations designed for use in multithreaded contexts: ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteArraySet.

除了队列,这个包提供了几个集合实现在多线程环境中设计用于:ConcurrentHashMapCopyOnWriteArrayList,和CopyOnWriteArraySet



This also comes in handy if you want to match the number of threads to the number of available CPUs for example:

如果您想将线程数与可用 CPU 数相匹配,这也很方便,例如:

int n = Runtime.getRuntime().availableProcessors();

回答by Gian

In most Java implementations, you can rely on Java threads being real OS threads. As a result, the operating system will take care of making sure that the workload is distributed across multiple cores if you use the Thread class.

在大多数 Java 实现中,您可以将 Java 线程视为真正的 OS 线程。因此,如果您使用 Thread 类,操作系统将负责确保工作负载分布在多个内核上。

Operating system threads pre-date commodity multicore systems by a long time, so that's not a concern really. The only difference multicore systems made was to allow time-multiplexed operating system threads to be executed as truly concurrent threads on multiple cores.

操作系统线程早于商用多核系统很长一段时间,所以这不是真正的问题。多核系统的唯一区别是允许时分复用操作系统线程作为多核上真正的并发线程来执行。

回答by Richard Kettelerij

Java 5 introduced the java.util.concurrent package which helps in building concurrent applications that can benefit from multicore systems. This package goes way beyond the multithreading functionality offered in Java 1.4 and earlier (like synchronized, wait, notify, etc).

Java 5 引入了 java.util.concurrent 包,它有助于构建可以从多核系统中受益的并发应用程序。这个包超越了 Java 1.4 及更早版本中提供的多线程功能(如同步、等待、通知等)。

There's a proposal for Java 7 to include the Fork/Joinframework to make use of multicore systems easier.

有一项提议让 Java 7 包含Fork/Join框架,以便更轻松地使用多核系统。

回答by Patrick Viry

You'll find newfunctionality in Ateji PX, an extension of the Java language with parallel primitives inspired from pi-calculus. Quite different from thread programming and everything thread-based (Tasks, Executors, etc).

您将在 Ateji PX 中找到功能,它是 Java 语言的扩展,具有受 pi 演算启发的并行原语。与线程编程和基于线程的一切(任务、执行程序等)完全不同。

Parallelism introduced this way at the language level, as opposed to threading librairies that provide API access to a mostly hardware-level concept, makes multicore programming much simpler and intuitive.

并行以这种方式在语言级别引入,与提供对主要硬件级别概念的 API 访问的线程库相反,使多核编程更加简单和直观。

It's a radically new approach to parallel programming worth reading about (disclaimer: I am the designer of Ateji PX). The whitepaper is here : http://www.ateji.com/px/whitepapers/Ateji%20PX%20for%20Java%20v1.0.pdf.

这是一种全新的并行编程方法,值得一读(免责声明:我是 Ateji PX 的设计者)。白皮书在这里:http: //www.ateji.com/px/whitepapers/Ateji%20PX%20for%20Java%20v1.0.pdf

回答by Ravindra babu

Yes. Java provides concurrent APIto avail advantages of multi-core processors of machine.

是的。Java 提供并发 API以利用机器的多核处理器的优势。

You can get available processors count from Runtime and use that count to create ExecutorServicethrough many APIs in Executors.

您可以从 Runtime 获取可用处理器计数,并使用该计数通过Executors 中的许多 API创建ExecutorService

You can also use ThreadPoolExecutorAPI to achieve the same.

您也可以使用ThreadPoolExecutorAPI 来实现相同的功能。

Java 8 provides one more API : newWorkStealingPool, which create ForkJoinPool by using all available processors. You don't have to pass processor count as parameter.

Java 8 提供了另一个 API:newWorkStealingPool,它使用所有可用的处理器创建 ForkJoinPool。您不必将处理器计数作为参数传递。

Have a look at sample to code:

看一下代码示例:

int processorCount = Runtime.getRuntime().availableProcessors();

ExecutorService executor1 = Executors.newFixedThreadPool(processorCount);
ExecutorService executor2 =  
                            Executors.newScheduledThreadPool(processorCount);
ExecutorService executor3 = Executors.newWorkStealingPool(); // java-8 API
ForkJoinPool forkJoinPool = new ForkJoinPool(processorCount);

Have a look at related SE question right Executor:

看看相关的 SE 问题吧 Executor:

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

Java 的 Fork/Join 与 ExecutorService - 何时使用哪个?