安卓平板多线程代码
时间: 2023-06-22 14:23:20 浏览: 50
以下是一个简单的安卓平板多线程代码示例,其中包含两个线程,一个用于计算斐波那契数列,另一个用于打印当前时间:
```java
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 fibonacciThread = new Thread(new Runnable() {
@Override
public void run() {
int n = 10;
int a = 0, b = 1, c;
for (int i = 1; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
// 在计算完成后更新 UI
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.setText("斐波那契数列第10项为:" + a);
}
});
}
});
// 创建打印当前时间线程
Thread timeThread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
final String time = DateFormat.getTimeInstance().format(new Date());
// 在 UI 线程中更新时间
runOnUiThread(new Runnable() {
@Override
public void run() {
mTextView.append("\n" + time);
}
});
try {
// 暂停 1 秒钟
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
// 启动两个线程
fibonacciThread.start();
timeThread.start();
}
}
```
在这个例子中,使用了 `Thread` 类创建两个线程,分别计算斐波那契数列和打印当前时间。在计算斐波那契数列的线程中,使用了 `runOnUiThread()` 方法来更新 UI 界面,以显示计算结果。在打印当前时间的线程中,使用了 `DateFormat` 类来获取当前时间,并使用 `Thread.sleep()` 方法来暂停线程一秒钟,以控制打印时间的频率。最后,通过调用 `start()` 方法启动两个线程。