本文實(shí)例講述了JavaScript使用yield模擬多線程的方法。分享給大家供大家參考。具體分析如下:
在python和C#中都有yield方法,通過yield可以實(shí)現(xiàn)很多多線程才能實(shí)現(xiàn)的功能。
對javascript有版本要求:JavaScript 1.7
function Thread( name ) { for ( var i = 0; i < 5; i++ ) { Print(name+': '+i); yield; }}//// thread managementvar threads = [];// thread creationthreads.push( new Thread('foo') );threads.push( new Thread('bar') );// schedulerwhile (threads.length) { var thread = threads.shift(); try { thread.next(); threads.push(thread); } catch(ex if ex instanceof StopIteration) {}}上面代碼輸入結(jié)果如下:
foo: 0bar: 0foo: 1bar: 1foo: 2bar: 2foo: 3bar: 3foo: 4bar: 4
希望本文所述對大家的javascript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答