Thread类-Flash中的线程概念

来源:互联网 发布:acronis备份软件 编辑:程序博客网 时间:2024/04/30 02:42
在最近Flash开发过程中,发现定时运行函数(setInterval)使用频率非常高,但这个方法用多了就比较混乱,不易管理,就要更好的方法了。然后我和同事商讨一个比较好的解决方案。我们就发现Java中线程是比较好的方法,于是我们就参照Java的Thread类,就写一个Flash的Thread类,这个类调用起来多了一两行代码,但是比较好控制和管理。和Java中Thread类非常相似。今天我也把它贴出来,希望对大家有一些帮助!

以下是Thread.as代码片段:
这个类不需要改直接使用;
/*
* Name:Thread.as
* Auther:Kinglong
* Email:kinglong@gmail.com
* Date:2005-04-20
* Desc:
* 线程的基类;
*/
class com.klstudio.util.Thread extends Object{
 private var __mar:Number;
 private var __sleep_time:Number;
 function Thread(sleepTime:Number){
  if(sleepTime == undefined){
   this.__sleep_time = 50;
  }else{
   this.__sleep_time = sleepTime;
  }
 }
 private function doRun():Void{
  this.run();
 }
 public function run():Void{  
 }
 public function start():Void{
  this.__mar = setInterval(this,"doRun",this.__sleep_time);
 }
 public function stop():Void{
  clearInterval(this.__mar);
 }
 public function setSleepTime(sleepTime:Number):Void{
  this.__sleep_time = sleepTime;
 }
 public function getSleepTime():Number{
  return this.__sleep_time;
 }
}
以下是testThread.as代码片段:
import com.klstudio.util.Thread;
class testThread extends Thread{
 private var __label_txt:TextField;
 function testThread(){
  super(1000);
  this.init();
 }
 private function init():Void{
  _root.createTextField("label_txt", 4, 0, 0, 100, 20);  
  this.__label_txt = _root["label_txt"];
  this.initLabel();
  this.start();
 }
 private function initLabel():Void{
  this.__label_txt.autoSize = "left";
  this.__label_txt.html = false;
  this.__label_txt.textColor = 0x000000;
  this.__label_txt.wordWrap = false;
  this.__label_txt.type = "dynamic";
  this.__label_txt.selectable = false;
 }
 private function run():Void{
  var today:Date = new Date();
  var lbl:String = (today.getHours() < 10 ? "0" + today.getHours() : today.getHours()) + ":" + (today.getMinutes() < 10 ? "0" + today.getMinutes() : today.getMinutes()) + ":" + (today.getSeconds() < 10 ? "0" + today.getSeconds() : today.getSeconds());
  this.__label_txt.text = lbl;
 }
}
以下是Flash调用代码片段:
stop();
var tt:testThread = new testThread();