async-threading让Flex支持多线程

开源项目async-threading能使as3支持多线程。

要在Flex4 sdk环境下使用,要先修改一下源代码,打开com.symantec.premiumServices.asyncThreading.handlers.FPSObserverHandler:

  • import mx.core.Application;修改为import spark.components.Application;
  • private var _appRef:Application = Application.applicationas Application;修改为private var _appRef:Application = FlexGlobals.topLevelApplication as Application;
  • 同时导入import mx.core.FlexGlobals;

这个api要求自定义的线程继承AbstractAsyncThread然后实现IAsyncThreadResponder接口,写一个测试用线程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package thread  
{
import com.symantec.premiumServices.asyncThreading.abstract.AbstractAsyncThread;
import com.symantec.premiumServices.asyncThreading.interfaces.IAsyncThreadResponder;

/**
* 自定义线程
*/
public class SelfDefinedThread extends AbstractAsyncThread implements IAsyncThreadResponder
{
private var f:Function;

public function SelfDefinedThread(f:Function)
{
super();
this.f = f;
}

public function execute():void
{
f.call();
}
}
}

这个api还是比较强大的,基本线程操作和通讯都能实现了,具体可以看附件内的源代码api。

这个线程的构造函数要传入一个方法,这个方法将在线程启动后调用。测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>  
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="testThread()">
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
</fx:Declarations>

<fx:Script>
<![CDATA[
import thread.SelfDefinedThread;

private function testThread():void{
//线程1
var thread1:SelfDefinedThread = new SelfDefinedThread(
function():void{
trace("线程1执行");
trace("开启线程2");
thread2.start();
});

//线程2
var thread2:SelfDefinedThread = new SelfDefinedThread(
function():void{
trace("线程2执行");
if(thread1.sleeping)
{
thread1.kill();
thread2.kill();
thread3.kill();
trace("线程1,2,3终止");
}else{
trace("开启一个线程3");
thread3.start();
}
});

//线程3
var thread3:SelfDefinedThread = new SelfDefinedThread(
function():void{
trace(thread3.id + "线程3执行");
if(!thread1.sleeping)
{
thread1.sleep();
trace("线程1休眠");
}
});
thread1.priority = thread1.RUN_LEVEL_HIGH;
thread2.priority = thread2.RUN_LEVEL_BELOW_NORMAL;
thread1.start();
}

]]>
</fx:Script>
<s:Label x="281" y="122" text="多线程测试"/>
</s:WindowedApplication>

用调试模式执行就能看到结果:

源代码下载:[MultiThreadingApp.rar] [MultiThreadTest.rar]

来发评论吧~
Powered By Valine
v1.5.2