啃"创建线程"一章的疑难解析: 通读Concurrent Programming in Java: Design Principles and Patterns (2)

来源:互联网 发布:Java怎么存储多条记录 编辑:程序博客网 时间:2024/05/02 01:56

每次打开"Concurrent Programming in Java: Design Principles and Patterns" 电子书,都会觉得此书充满智慧. 对于程序员来说, 了解多种的技术不是坏事, 但如果每种技术都理解不深刻, 那也不是什么好事, 只有把每个技巧后面的模型弄透, 搞清楚了几种模型的对比, 才能做到融会贯通. 这本书不是简单的讲技巧, 也不会深入的讲模型, 一切都恰到好处; 给你"学"的机会和"思"的空间.

"创建线程"(create thread)一章讲的是对线程模型的理解,  及如何创建线程, 最后又抛开线程说对待并行程序的观点.开始读这章时没读几段就看不懂了, 看书时比较躁, 后来越看越不懂, 直到第二天, 对于其中一些概念才能说是略有理解.

1. Task-based and Actor-based

原文是这样的"Task-based Here, the main reason to use a thread is to asynchronously invoke a method that performs some task. The task might range from a single method to an entire session. Thread-based techniques can support message-passing schemes that escape the limitations of pure procedural calls. Task-based designs are seen in event frameworks, parallel computation, and IO-intensive systems.

Actor-based Here, the main reason to use a thread is to create and set into motion a new autonomous, active, process-like object. This object may in turn react to external events, interact with other actors, and so on. Actor-based designs are seen in reactive, control, and distributed systems. They are also the focus of most formal approaches to concurrency." 第一遍看根本看不出个所以然来,  后来是先搞清楚"autonomous"是自治的意思, 这里又有一个"process-like", 所以说这里的Actor-based指的是创建一个线程, 使它与其它线程(也是Actor-based的)的关系就像进程间的关系一样, 没有Shared-memory. 也就是说, Actor-based线程要创建一个像进程一样的线程.

2. Passive Message 和 Active Message; Passive Object 和 Active Object.

原文是这样"In task-based systems, passive objects sometimes send active (thread-propelled) messages, while in actor-based systems, active objects normally send passive messages" 我是这样理解的, Passive objects 是指在Shared Memory中存放的对象, 而active objects指的则是thread对象. active message指的是可被线程驱动的(thread-propelled)对象(通常就是像Runnable这样的东东). passive messages就是指除active message之外的被用来传递的对象了. 这些解释大概是对的了, 可是整句话怎么就搞不太懂了呢? 其实看了本章第四节后, 才明白这名句话应该说成"In task-based systems, sometimes send active (thread-propelled) messages among passive objects , while in actor-based systems, normally send passive messages among active objects "就是说: 当一个 passive object给另一个 passive object传递东东时, 有时(有时用的好)传的是runnable, 而对于 actor-based systems, 每个线程(像进程一样的线程)传递的,就通常是Runnable了.

本章最后提的JCSP挺赖人寻味的, 视其为技巧, 很精妙, 视其为模型, 很漂亮.好像Sogou labs里的一些资料提到的C10K问题(http://www.sogou.com/labs/reports.html)的解决方案好像就符合些模型. 可以google一下JCSP, 会有很多收获. 很多时候, 我们已经使用了某些技巧, 可是我们并不知道它其实符合某些模型, 但这对于产品似乎无足轻重.