随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
layout文件:
<?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.PractiseActivity4"
android:orientation="vertical"> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvw1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvw2"/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btt1"
android:text="随机选择"
android:onClick="btn_onClick"/>
</LinearLayout>
java类:
package com.hanqi.testapp2; import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast; public class PractiseActivity4 extends AppCompatActivity { TextView tvw1;
Button btt1;
TextView tvw2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_practise4);
tvw1 = (TextView)findViewById(R.id.tvw1);
btt1 = (Button)findViewById(R.id.btt1);
tvw2 = (TextView)findViewById(R.id.tvw2);
}
String c1 = "北京";
String c2 = "上海";
public void btn_onClick(View v)
{
//创建子线程1
new Thread(){
@Override
public void run() {
for (int i=0;i<20;i++)
{
if(i%2==0)
{
c1="";
}
else
{
c1="北京";
}
runOnUiThread(new Runnable() {
@Override
public void run() {
tvw1.setText(c1);
}
});
//暂停
try {
Thread.sleep((int) (Math.random()*1000));
}
catch (Exception e)
{ }
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PractiseActivity4.this, c1 + "循环完成", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
//创建子线程2
new Thread(){
@Override
public void run() {
for (int i=0;i<20;i++)
{
if(i%2==0)
{
c2="";
}
else
{
c2="上海";
}
runOnUiThread(new Runnable() {
@Override
public void run() {
tvw2.setText(c2);
}
});
//暂停
try {
Thread.sleep((int) (Math.random()*1000));
}
catch (Exception e)
{ }
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PractiseActivity4.this, c2 + "循环完成", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
} }
随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。