多线程编程 1.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.hanqi.testapp2.duoxianchengActivity" 11 android:orientation="vertical"> 12 13 <Button 14 android:layout_width="match_parent" 15 android:layout_height="wrap_content" 16 android:text="点击选择" 17 android:id="@+id/btt_1" 18 android:onClick="btt1_OnClick"/> 19 20 </LinearLayout>
package com.hanqi.testapp2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.util.Random; public class duoxianchengActivity extends AppCompatActivity { Button btt_1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_duoxiancheng); btt_1=(Button)findViewById(R.id.btt_1); } Random random=new Random(); public void btt1_OnClick(View v) { for (int i = 0; i < 10; i++) { new Thread() { @Override public void run() { try { Thread.sleep(random.nextInt(1000)); } catch (Exception e) { } runOnUiThread(new Runnable() { @Override public void run() { btt_1.setText("淄博"); } }); return; } }.start(); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(random.nextInt(1000)); } catch (Exception e) { } runOnUiThread(new Runnable() { @Override public void run() { btt_1.setText("青岛"); } }); return; } }).start(); } } }