多线程
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.hanqi.testapp2.TestActivity6" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="城市1" android:id="@+id/tv_3"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="城市2" android:id="@+id/tv_4"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="启动" android:onClick="bt1_OnClick"/> </LinearLayout>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.hanqi.testapp2; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.TextView; import android.widget.Toast; import java.util.Random; public class TestActivity6 extends AppCompatActivity { TextView tv_3; TextView tv_4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test6); tv_3=(TextView)findViewById(R.id.tv_3); tv_4=(TextView)findViewById(R.id.tv_4); } String c1="北京"; String c2="香港"; public void bt1_OnClick(View v) { tv_3.setText(""); tv_4.setText(""); //创建子线程1 new Thread(){ @Override public void run() { for (int i=0;i<10;i++) { runOnUiThread(new Runnable() { @Override public void run() { tv_3.setText(tv_3.getText()+c1); } }); try { //暂停时间随机 Thread.sleep(new Random().nextInt(2000)); } catch (Exception e) { } } runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(TestActivity6.this,c1+ "循环完成", Toast.LENGTH_SHORT).show(); } }); } }.start(); //创建子线程2 实现接口 new Thread(){ @Override public void run() { for (int i=0;i<10;i++) { runOnUiThread(new Runnable() { @Override public void run() { tv_4.setText(tv_4.getText()+c2); } }); try { //暂停时间随机 Thread.sleep(new Random().nextInt(2000)); } catch (Exception e) { } } runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(TestActivity6.this,c2+ "循环完成", Toast.LENGTH_SHORT).show(); } }); } }.start(); } }