AS3 多线程

来源:互联网 发布:mysql 连接远程数据库 编辑:程序博客网 时间:2024/04/30 03:41
package{import flash.display.Sprite;import flash.events.Event;import flash.system.MessageChannel;import flash.system.Worker;import flash.system.WorkerDomain;import flash.utils.setInterval;public class HelloWorldWorker extends Sprite{protected var mainToWorker:MessageChannel;protected var workerToMain:MessageChannel;protected var worker:Worker;public function HelloWorldWorker(){/**  * Start Main thread **/if(Worker.current.isPrimordial){//Create worker from our own loaderInfo.bytesworker = WorkerDomain.current.createWorker(this.loaderInfo.bytes);//Create messaging channels for 2-way messagingmainToWorker = Worker.current.createMessageChannel(worker);workerToMain = worker.createMessageChannel(Worker.current);//Inject messaging channels as a shared propertyworker.setSharedProperty("mainToWorker", mainToWorker);worker.setSharedProperty("workerToMain", workerToMain);//Listen to the response from our workerworkerToMain.addEventListener(Event.CHANNEL_MESSAGE, onWorkerToMain);//Start worker (re-run document class)worker.start();//Set an interval that will ask the worker thread to do some mathsetInterval(function(){mainToWorker.send("ADD");mainToWorker.send(2);mainToWorker.send(2);}, 1000);} /**  * Start Worker thread  **/else {//Inside of our worker, we can use static methods to //access the shared messgaeChannel'smainToWorker = Worker.current.getSharedProperty("mainToWorker");workerToMain = Worker.current.getSharedProperty("workerToMain");//Listen for messages from the mian threadmainToWorker.addEventListener(Event.CHANNEL_MESSAGE, onMainToWorker);}}//Main >> Workerprotected function onMainToWorker(event:Event):void {var msg:* = mainToWorker.receive();//When the main thread sends us HELLO, we'll send it back WORLDif(msg == "HELLO"){workerToMain.send("WORLD");}else if(msg == "ADD"){//Receive the 2 numbers and add them togethervar result:int = mainToWorker.receive() + mainToWorker.receive();//Return the result to the main threadworkerToMain.send(result);}}//Worker >> Mainprotected function onWorkerToMain(event:Event):void {//Trace out whatever message the worker has sent us.trace("[Worker] " + workerToMain.receive());}}}
0 0
原创粉丝点击