Java中的并发性和并行性之间有区别吗?

编程入门 行业动态 更新时间:2024-10-09 08:34:52
本文介绍了Java中的并发性和并行性之间有区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在Google进行一些研究,无法完全理解Java中并发程序和并行程序之间的差异(如果有).我查看的一些信息表明两者之间没有区别.是这样吗?

I have been doing some research in Google and cant quite get my head around the differences (if any) between concurrent and parallel programs in java. Some of the information I have looked at suggests no differences between both. Is this the case??

推荐答案

这取决于谁在定义它.创建Go编程语言调用代码并发的人分成可以并行处理的片段,而并行性则意味着这些片段实际上是同时运行的.

It depends on who is defining it. The people who created the Go programming language call code Concurrent if it is broken up into pieces which could be treated in parallel, whereas Parallelism implies that those pieces are actually running at the same time.

由于这些是编程原则,因此编程语言与如何定义它们无关.但是,Java 8将具有更多功能,以同时启用并发和并行性,而不会过多地破坏您的代码.例如,如下代码:

Since these are programming principles, the programming language has no bearing on how they are defined. However, Java 8 will have more features to enable both concurrency and parallelism without messing up your code too much. For example, code like this:

List<Integer> coolItemIds = new List<Integer>(); for(Item item : getItems()) { if(item.isCool()) { int itemId = item.getId(); coolItemIds.add(item); } }

...是非并行且非并行的,可以这样写(我的语法可能是错误的,但希望您能理解):

... which is non-concurrent and non-parallel, could be written like this (my syntax is probably wrong, but hopefully you get the idea):

Iterable<Item> items = getItems(); Iterable<Item> coolItems = items.filter(item -> item.isCool()); Iterable<Integer> coolItemIds = coolItems.map(item -> item.getId());

上面的代码是以 concurrent 的方式编写的:给定的代码均不需要一次将coolItem过滤一次,或者您只能调用 getId()一次放在一个项目上,甚至需要过滤或映射列表开头的项目,而不是在结尾的项目之前进行过滤或映射.取决于从 getItems()返回的 Iterable 类型,给定的操作可能会或可能不会并行运行 ,但是您所使用的代码写的是并发.

The above code is written in a concurrent manner: none of the given code requires that the coolItems be filtered one at a time, or that you can only call getId() on one item at a time, or even that the items at the beginning of the list need to be filtered or mapped before items at the end. Depending on what type of Iterable is returned from getItems(), the given operations may or may not run in parallel, but the code you've written is concurrent.

也很有趣:

  • 并发不是并行性(演示视频)
  • 并发不是并行性吗?(讨论StackOverflow
  • Concurrency is not Parallelism (presentation video)
  • Concurrency is not Parallelism? (Discussion on StackOverflow

更多推荐

Java中的并发性和并行性之间有区别吗?

本文发布于:2023-11-23 21:29:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   发性   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!