Thread跟Handler一起用的线程

首先,建立一个Thread线程

new Thread() {
				public void run() {
					try {
						for (int i = 0; i < 100; i++) {
							Message msg = new Message();//建立消息处理机制
							msg.what =1;
							msg.arg1 = i;
							handler.sendMessage(msg);//发送msg
							Thread.sleep(100); //暂停0.1s
						}
					} catch (Exception e) {
						// TODO: handle exception
					}

				};
			}.start();   //.start();一定要用到,不然启动不了

然后用Handler机制接收线程

Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				
				text.setText(msg.arg1+"");
				break;

			default:
				break;
			}
		};
	};

以上是一个从1到99数字显示的线程代码。

猜你喜欢

转载自blog.csdn.net/weixin_44931166/article/details/96826961