进程:Process
线程:Thread
摘自Stackoverflow
Both processes and threads are independent sequences of execution.
The typical difference is that threads (of the same process) run in a shared memory space,
while processes run in separate memory spaces.
进程和线程都是独立的执行序列。
典型的区别在于(相同进程的)线程运行在一个共享内存空间,进程运行在单独的内存空间。
Html5 Web Workers API 与thread 线程的概念相关联
A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file — this file contains the code that will run in the worker thread; workers run in another global context that is different from the current window. Thus, using the window shortcut to get the current global scope (instead of self) within a Worker will return an error.
worker是使用运行命名的JavaScript文件的构造函数(例如Worker())创建的对象 - 此文件包含将在工作线程中运行的代码; wokers在与当前窗口不同的另一全局上下文中运行。 因此,使用窗口快捷方式在Worker中获取当前全局范围(而不是self)将返回错误。
直接通过实践理解这句话:
创建 file.js
var i = 0;
function counter() {
i = i + 1;
postMessage(i);
setTimeout(counter, 500);
}
counter();
html不分代码
<button onclick="start()">Start</button>
<button onclick="end()">End</button>
<div id="result"></div>
主页的js部分代码
var worker,
result = document.getElementById('result');
function start() {
if(typeof (Worker) === "undefined") { //判断你浏览器是否支持 Worker
worker = new Worker("file.js");
worker.onmessage = function(event) {
result.innerHTML = event.data // 传递过来的i值 被储存在event.data中
}
} else {
result.innnerHTML = "你的浏览器不支持 Web Worker";
}
}
function end() {
worker.terminate();
}
主要用到了 Web Worker 全局下的 postMessage( ) 向HTML中传递数据。
通常用到Web Worker的地方是需要消耗CPU很多时间的任务, 这样可以不阻塞主线程继续执行。