2013年js就支持多线程执行

新建一个index.html

while (1) {
    console.log(Math.random());
}
1
2
3

页面会执行卡死

简单的js多线程例子

//index.html

var worker = new Worker('myworker.js')
    worker.onmessage = function (evf) {
    console.log(evf.data);
}
1
2
3
4

//新建mywork.js

while (1) {
    postMessage(Math.random());
}
1
2
3

需要本地起个服务访问index.html

下一个示例

//ArrayBuffer 代表内存中一段二进制数据 //TypedArray 9中类型 Int32Array Float64Array //DataView 复合形式数据类型 index.html

var worker = new Worker('myworker.js')
worker.onmessage = function (evf) {
    //新建1kb 共享内存

}
//构建一个视图 写入数据
//10万个32位 整数占据的连续的内容空间
const shareBuffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * 1000)
const ia = new Int32Array(shareBuffer)
for (let i = 0; i < ia.length; i++) {
    ia[i] = i;
}

worker.postMessage(shareBuffer)
1
2
3
4
5
6
7
8
9
10
11
12
13
14

index.js

let ia;
console.log(121212)
onmessage = function (evf) {
    console.log(11111);
    ia = evf.data
    console.log(ia[37]);
}
1
2
3
4
5
6
7