android studio 按照顺序执行线程,请给出代码示例
时间: 2023-04-06 14:00:24 浏览: 103
以下是一个简单的示例代码,演示如何按照顺序执行线程:
```
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = findViewById(R.id.text_view);
// 创建三个线程
Thread thread1 = new Thread(new MyRunnable("线程1"));
Thread thread2 = new Thread(new MyRunnable("线程2"));
Thread thread3 = new Thread(new MyRunnable("线程3"));
// 依次启动三个线程
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread2.start();
try {
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread3.start();
try {
thread3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class MyRunnable implements Runnable {
private String mName;
public MyRunnable(String name) {
mName = name;
}
@Override
public void run() {
// 在这里编写线程的逻辑
for (int i = 0; i < 5; i++) {
final String text = mName + "执行了第" + (i + 1) + "次";
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.append(text + "\n");
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
这个示例代码中,我们创建了三个线程,分别执行了一些简单的逻辑。在 `onCreate` 方法中,我们依次启动了这三个线程,并使用 `join` 方法等待每个线程执行完毕。这样,就可以保证这三个线程按照顺序执行。
阅读全文