Android java多线程,线程的创建和启动。
方法一:继承Thread类创建线程类
方法二:实现Runnable接口创建线程类。
方法三:使用Callable和Future创建线程。
效果图
ThreadActivity.java
package com.example.androidthread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class ThreadActivity extends Activity
{
TextView txtShow1,txtShow2,txtShow3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread);
txtShow1=(TextView)findViewById(R.id.txtShow1);
txtShow2=(TextView)findViewById(R.id.txtShow2);
txtShow3=(TextView)findViewById(R.id.txtShow3);
//启动线程(继承Thread类)
new FirstThread().start();
//启动线程(实现Runnable接口)
new Thread(new SecondThread(),"Thread-2").start();
//启动线程(实现Callable接口)
FutureTask<String> task=new FutureTask<String>(new ThirdThread());
new Thread(task,"Thread-3").start();
try
{
//得到call()方法返回值
txtShow3.append(task.get());
} catch (InterruptedException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (ExecutionException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
//继承Thread类创建线程类
public class FirstThread extends Thread
{
public void run()
{
Thread.currentThread().setName("Thread-1");
txtShow1.setText(Thread.currentThread().getName()+" extends Thread");
}
}
//实现Runnable接口创建线程类
public class SecondThread implements Runnable
{
public void run()
{
txtShow2.setText(Thread.currentThread().getName()+" implements Runnable");
}
}
//使用Callable和Future创建线程类
public class ThirdThread implements Callable<String>
{
public String call()
{
txtShow3.setText(Thread.currentThread().getName());
return " implements Callable";
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.thread, menu);
return true;
}
}
activity_thread.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
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"
android:orientation="vertical">
<TextView
android:id="@+id/txtShow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<TextView
android:id="@+id/txtShow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="txtShow2"/>
<TextView
android:id="@+id/txtShow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="txtShow3"/>
</LinearLayout>
</ScrollView>