Java中的并发性和并行性之间有区别吗? [英] Is there a difference between concurrency and parallelism in java?

查看:55
本文介绍了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.

也很有趣:

  • Concurrency is not Parallelism (presentation video)
  • Concurrency is not Parallelism? (Discussion on StackOverflow

这篇关于Java中的并发性和并行性之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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