Android Thread

来源:互联网 发布:排序二叉树的建立c语言 编辑:程序博客网 时间:2024/06/05 19:34

创建新线程的常用方式:

   1. 直接使用Thread创建
       Thread thread = new Thread();
       thread.start();
  2. 扩展java.lang.Thread类
       Thread类的定义public class Threadextends Object implements Runnable(){…}
扩展Thread类的实质其实也是实现Runnable接口,只不过Thread类继承了Object类方法
  3. 实现Runnable接口

具体代码:

  1. 扩展java.lang.Thread类

public class test3_4  extends Activity  {    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        MyThread myThread = new MyThread();        myThread.start();    }    class MyThread extends Thread{         public void run() {            System.out.println("zz");        }     }}

注:看见网上有人举这个例子
        MyThread myThread = new MyThread();
        myThread.start();
        myThread.start();
        myThread.start();
我在模拟器上测试了运行不过,不能得到预期结果。不知道为什么!runnable的也不行!

2. 实现Runnable接口

public class test3_4  extends Activity {    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        MyThread myThread = new MyThread();        new Thread(myThread).start();    }    class MyThread implements Runnable{        public void run() {            System.out.println("zz");        }       }}

或者

public class test3_4  extends Activity implements OnClickListener, Runnable{     private Button button;     private TextView text;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        button = (Button)findViewById(R.id.button);        text = (TextView)findViewById(R.id.text);        button.setOnClickListener(this);    }    public void onClick(View v) {        Thread thread = new Thread(this);        thread.start();    }    public void run() {        System.out.println("zz");    }}
原创粉丝点击