码迷,mamicode.com
首页 > 编程语言 > 详细

通过Handler与线程嵌套TimerTask实现循环交替任务

时间:2015-07-24 18:33:55      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:java   enum   android   

创建两个循环交替任务:10秒后,A任务执行。 A任务里面创建一个B任务200毫秒后执行,B任务里面又创建一个A任务10秒后执行,如此往复。

1,首先采用Handler与线程的sleep(long)方法;

    Handler主要用来处理接受到的消息。这只是最主要的方法,当然Handler里还有其他的方法供实现,有兴趣的可以去查API,这里不过多解释。

1. 定义一个Handler类,用于处理接受到的Message。

  1. Handler handler = new Handler() {  
  2.     public void handleMessage(Message msg) {  
  3.         // 要做的事情  
  4.         super.handleMessage(msg);  
  5.     }  
  6. };  
2. 新建一个实现Runnable接口的线程类,如下:
  1. public class MyThread implements Runnable {  
  2.     @Override  
  3.     public void run() {  
  4.         // TODO Auto-generated method stub  
  5.         while (true) {  
  6.             try {  
  7.                 Thread.sleep(10000);// 线程暂停10秒,单位毫秒  
  8.                 Message message = new Message();  
  9.                 message.what = 1;  
  10.                 handler.sendMessage(message);// 发送消息  
  11.             } catch (InterruptedException e) {  
  12.                 // TODO Auto-generated catch block  
  13.                 e.printStackTrace();  
  14.             }  
  15.         }  
  16.     }  
  17. }  

3. 在需要启动线程的地方加入下面语句:

new Thread(new MyThread()).start();  

4.测试类

import java.util.Date;  
import java.util.Timer;  
import java.util.TimerTask;  
  
/** 
 * @author Administrator  
 */  
public class TraditionalTime2 {  
      
    /* 
     * 创建两个循环交替任务:10秒后,A任务执行。 
     * A任务里面创建一个B任务200毫秒后执行,B任务里面又创建一个A任务10秒后执行,如此往复。 
     *  
     */  
    public static void main(String[] args) {  
        TraditionalTime2 t2=new TraditionalTime2();  
        new Timer().schedule(t2.new A(), 10000);  
          
         //用于打印时间秒数  
        while (true) {  
            System.out.println(new Date().getSeconds());  
            try {  
                Thread.sleep(1000);  
            } catch (InterruptedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
        }  
    }  
    class A extends TimerTask {  
        @Override  
        public void run() {  
            System.out.println("A bombing!");  
            new Timer().schedule(new B(), 200);  
  
        }  
  
    }  
  
    class B extends TimerTask {  
        @Override  
        public void run() {  
            System.out.println("B bombing!");  
            new Timer().schedule(new A(), 10000);  
  
        }  
    }  
}  

完整代码:

	/**
	 * 每隔10s发一次整包查询请求,10秒后,A(发送整个包查询)任务执行。
	 * A(发送整包查询)任务里面创建一个B(发送查询一个ID包)任务200毫秒后执行
	 */
	// 查询数据
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// 要做的事情发送查询请求
			System.out.println("每隔10s发一次查询包请求");
			/**
			 * 枚举类型的遍历 
			 * 间隔200ms,发下一个包;
			 */
			PackageId[] allPackageId = PackageId.values();
			for (PackageId aPackageId : allPackageId) {
//				System.out.println("200ms发一次查询id!");
				System.out.println(" 当前名字: " + aPackageId.name());
				System.out.println(" 当前序号: " + aPackageId.ordinal());
				// System. out .println( " 当前: " + aPackageId);
				byte[] data = { 0x01 };
				PumpPackage myPackage = new PumpPackage(aPackageId, data);
				util.writePort(myPackage.getSendArray());
				// new Thread(new QueryThread()).start();
				new Timer().schedule(new QueryPackageId(), 5000);//QueryPackageId 200毫秒后执行
			}
			
			super.handleMessage(msg);
		}
	};

	public class QueryThread implements Runnable {
		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(10000);// 线程暂停10秒,单位毫秒
					Message message = new Message();
					message.what = 1;
					handler.sendMessage(message);// 发送消息
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 间隔200毫秒发一个包id查询请求
	 * @author sooner
	 *
	 */
	class QueryPackageId extends TimerTask {
		@Override
		public void run() {			
			System.out.println("200ms发一次查询id!");
		}
	}

@Override
public void didPackageReceived(blePort port, byte[] Received) {


// 接收到数组 解码为包
PumpPackage package1 = new PumpPackage(Received);
// 返回数据有问题
if (package1.isValid()) {
mReceivedData = package1.toString();
mReceivedId = package1.getPackageId();
// mReceivedValue =package1.getDataArray().toString();
// 包中需要的数据部分
try {
mReceivedValue = PumpPackage.bytesToInt(package1
.getDataArray());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(mReceivedData);
System.out.println(mReceivedId);
System.out.println(mReceivedValue);
//
cs = String.valueOf(mReceivedValue);
System.out.println(cs);
// 接收到数据后更新UI状态
PumpFragmentConnect.updateUiObjectState();
PumpFragmentConnect.runRow();
PumpFragmentConnect.updateUiObject((String) cs);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
PumpFragmentConnect.updateUiObject((String) cs);
// mLastSecondTotalReceiveSize = mTotalReceiveSize;
}
});
}


调试记录:

07-24 17:49:50.169: I/System.out(5251):  当前名字: UMToSlave_QuerySeq
07-24 17:49:50.169: I/System.out(5251):  当前序号: 15
07-24 17:49:50.179: D/ACSUtilityService(5251): There are 1 datas to be sended...
07-24 17:49:50.179: D/ACSUtilityService(5251): sending data...count0
07-24 17:49:50.179: D/ACSUtilityService(5251): writePort 1
07-24 17:49:50.179: D/ACSUtilityService(5251): writePort 2
07-24 17:49:50.179: D/ACSUtilityService(5251): writePort 3
07-24 17:49:50.179: D/ACSUtilityService(5251): writePort 4
07-24 17:49:50.179: D/ACSUtilityService(5251): data: [B@42afd448
07-24 17:49:50.179: D/BluetoothGatt(5251): writeCharacteristic() - uuid: 0000ffb2-0000-1000-8000-00805f9b34fb
07-24 17:49:50.189: D/BluetoothGatt(5251): onCharacteristicWrite() - Device=B4:99:4C:6E:33:1B UUID=0000ffb2-0000-1000-8000-00805f9b34fb Status=0
07-24 17:49:50.189: D/ACSUtilityService(5251): onCharacteristicWrite
07-24 17:49:50.189: D/ACSUtilityService(5251): notify workerThread
07-24 17:49:50.189: D/ACSUtilityService(5251): synchronized...
07-24 17:49:50.189: D/ACSUtilityService(5251): send succeed
07-24 17:49:50.189: E/ACSUtility(5251): EventHandler got a message.flag is 8
07-24 17:49:52.649: D/BluetoothGatt(5251): onNotify() - Device=B4:99:4C:6E:33:1B UUID=0000ffb2-0000-1000-8000-00805f9b34fb
07-24 17:49:52.649: D/ACSUtilityService(5251): onCharacteristicChanged
07-24 17:49:52.649: D/ACSUtilityService(5251): data line : length = 10
07-24 17:49:52.659: E/ACSUtility(5251): EventHandler got a message.flag is 5
07-24 17:49:52.659: W/System.err(5251): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
07-24 17:49:52.659: W/System.err(5251): at com.brio.bluetooth.PumpPackage.bytesToInt(PumpPackage.java:234)
07-24 17:49:52.659: W/System.err(5251): at com.brio.activity.StartActivity$1.didPackageReceived(StartActivity.java:186)
07-24 17:49:52.659: W/System.err(5251): at com.brio.util.ACSUtility$2.handleMessage(ACSUtility.java:136)
07-24 17:49:52.659: W/System.err(5251): at android.os.Handler.dispatchMessage(Handler.java:102)
07-24 17:49:52.659: W/System.err(5251): at android.os.Looper.loop(Looper.java:136)
07-24 17:49:52.659: W/System.err(5251): at android.app.ActivityThread.main(ActivityThread.java:5050)
07-24 17:49:52.659: W/System.err(5251): at java.lang.reflect.Method.invokeNative(Native Method)
07-24 17:49:52.659: W/System.err(5251): at java.lang.reflect.Method.invoke(Method.java:515)
07-24 17:49:52.659: W/System.err(5251): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-24 17:49:52.659: W/System.err(5251): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
07-24 17:49:52.659: W/System.err(5251): at dalvik.system.NativeStart.main(Native Method)
07-24 17:49:52.659: I/System.out(5251): id:  UpperMoni_CmdInValid  length: 1  data: [-86, -69, 2, 0, 1, 102, -60, -12, -26, -73]
07-24 17:49:52.659: I/System.out(5251): UpperMoni_CmdInValid
07-24 17:49:52.659: I/System.out(5251): 0
07-24 17:49:52.659: I/System.out(5251): 0

版权声明:本文为博主原创文章,未经博主允许不得转载。

通过Handler与线程嵌套TimerTask实现循环交替任务

标签:java   enum   android   

原文地址:http://blog.csdn.net/u010963246/article/details/47042603

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!