这是一个深思熟虑的设计决定,还是我们当前浏览器的一个问题,这个问题将在未来的版本中得到纠正?
当前回答
正如matt b所说,这个问题不是很清楚。假设您正在询问语言中的多线程支持:因为目前在浏览器中运行的99.999%的应用程序都不需要多线程。如果你真的需要它,有一些变通方法(比如使用window.setTimeout)。
一般来说,多线程是非常,非常,非常,非常,非常,非常,很难(我说过它很难吗?),除非你加入额外的限制(比如只使用不可变数据)。
其他回答
然而,你可以使用eval函数在一定程度上带来并发性
/* content of the threads to be run */
var threads = [
[
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');",
"document.write('Foo <br/>');"
],
[
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');",
"document.write('Bar <br/>');"
]
];
window.onload = function() {
var lines = 0, quantum = 3, max = 0;
/* get the longer thread length */
for(var i=0; i<threads.length; i++) {
if(max < threads[i].length) {
max = threads[i].length;
}
}
/* execute them */
while(lines < max) {
for(var i=0; i<threads.length; i++) {
for(var j = lines; j < threads[i].length && j < (lines + quantum); j++) {
eval(threads[i][j]);
}
}
lines += quantum;
}
}
据我所知,谷歌Chrome将有多线程javascript,所以这是一个“当前实现”的问题。
你的意思是为什么语言不支持多线程,或者为什么浏览器中的JavaScript引擎不支持多线程?
第一个问题的答案是,浏览器中的JavaScript是在沙盒中运行的,以一种独立于机器/操作系统的方式运行,添加多线程支持会使语言变得复杂,并将语言与操作系统联系得太紧密。
它的实现不支持多线程。目前谷歌Gears提供了一种通过执行外部进程来使用某种形式的并发的方法,但仅此而已。
新的浏览器谷歌应该今天发布(谷歌Chrome)通过在进程中分离一些代码并行执行。
当然,核心语言可以提供与Java相同的支持,但对Erlang并发性之类的支持还远远不够。
我不知道这个决定的基本原理,但我知道可以使用setTimeout模拟多线程编程的一些好处。您可以给人一种错觉,认为多个进程同时在做事情,但实际上,所有事情都发生在一个线程中。
只需要让你的函数做一点工作,然后调用类似这样的东西:
setTimeout(function () {
... do the rest of the work...
}, 0);
任何其他需要做的事情(如UI更新,动画图像等)都会在他们有机会的时候发生。