android 创建线程
时间: 2023-07-28 11:51:17 浏览: 42
在 Android 应用程序中,创建线程的方式有以下三种:
1. 继承 Thread 类并重写 run() 方法
```
public class MyThread extends Thread {
@Override
public void run() {
// 执行耗时操作
}
}
```
2. 实现 Runnable 接口并重写 run() 方法
```
public class MyRunnable implements Runnable {
@Override
public void run() {
// 执行耗时操作
}
}
```
然后在主线程中使用 Thread 类来创建线程并启动:
```
Thread thread = new Thread(new MyRunnable());
thread.start();
```
3. 使用 AsyncTask 类(适用于轻量级的异步操作)
```
public class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
// 执行耗时操作
return null;
}
}
```
然后在主线程中创建并执行 AsyncTask:
```
MyTask task = new MyTask();
task.execute();
```