【Android开发】线程与消息处理-通过实现Runnable接口来创建线程

来源:互联网 发布:华为v8连上数据不能上 编辑:程序博客网 时间:2024/05/28 05:14
利用Runnabe接口来创建线程,实现这样一个效果:在屏幕上有一个"开始"和一个"结束"按钮,单击"开始"按钮,将在日志(Log)面板中输出循环变量的值;单击"停止"按钮,将终端线程。

界面资源文件:
rea/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/linearLayout1"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >        <Button            android:id="@+id/button1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="开始" />                 <Button            android:id="@+id/button2"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="结束" /></LinearLayout>

界面效果如图




MainActivity:
package com.example.test;    import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;  public class MainActivity extends Activity implements Runnable{  private Thread thread;int i=0;    @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.main);        Button startButton=(Button)findViewById(R.id.button1);//获取开始按钮        startButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) { i=0;thread=new Thread(MainActivity.this);//创建一个线程thread.start();//开启线程}});                Button endButton=(Button)findViewById(R.id.button2);//获取结束按钮        endButton.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) { if(thread!=null){ thread.interrupt();//中断线程 thread=null; } Log.i("提示:", "中断线程");}});}@Overridepublic void run() {while(!Thread.currentThread().isInterrupted()){i++;Log.i("循环变量", String.valueOf(i));}}@Overrideprotected void onDestroy() { if(thread!=null){ thread.interrupt();//中断线程 thread=null; } Log.i("提示:", "因Activity结束中断线程");super.onDestroy();}}

运行结果和按键之后的效果如图所示


转载请注明出处:http://blog.csdn.net/acmman/article/details/46337017

0 0
原创粉丝点击