1 <LinearLayout 2 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 tools:context=".MainActivity" 7 android:orientation="vertical" 8 > 9 10 <Button 11 android:id="@+id/button01" 12 android:layout_width="match_parent" 13 android:layout_height="wrap_content" 14 android:text="第一種方式啓動子線程" 15 /> 16 17 <Button 18 android:id="@+id/button02" 19 android:layout_width="match_parent" 20 android:layout_height="wrap_content" 21 android:text="第二種方式啓動子線程" 22 /> 23 24 <Button 25 android:id="@+id/button03" 26 android:layout_width="match_parent" 27 android:layout_height="wrap_content" 28 android:text="第三種方式啓動子線程" 29 /> 30 31 </LinearLayout>
1 package zst.zst.thread01; 2 import java.util.TreeMap; 3 import android.os.Bundle; 4 import android.app.Activity; 5 import android.view.View; 6 import android.view.View.OnClickListener; 7 import android.widget.Button; 8 public class MainActivity extends Activity implements OnClickListener{ 9 private Button button01; 10 private Button button02; 11 private Button button03; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 button01 = (Button)findViewById(R.id.button01); 18 button02 = (Button)findViewById(R.id.button02); 19 button03 = (Button)findViewById(R.id.button03); 20 button01.setOnClickListener(this); 21 button02.setOnClickListener(this); 22 button03.setOnClickListener(this); 23 24 //主線程ID 25 System.out.println("主線程的ID-----> " + String.valueOf(Thread.currentThread().getId())); 26 } 27 @Override 28 public void onClick(View v) { 29 switch (v.getId()) { 30 case R.id.button01: 31 //第一種啓動子線程的方法 32 FirstThread firstThread = new FirstThread(); 33 firstThread.start(); 34 35 break; 36 case R.id.button02: 37 //第二種啓動子線程的方法 38 SecondThread secondThread = new SecondThread(); 39 new Thread(secondThread).start(); 40 41 break; 42 case R.id.button03: 43 //第三種啓動子線程的方法,和第二種方法是同一種啓動方法,只不過這裏用匿名內部類,這種方法最多見 44 new Thread(new Runnable() { 45 46 @Override 47 public void run() { 48 System.out.println("第三個子線程的ID---> " + String.valueOf(Thread.currentThread().getId())); 49 } 50 }).start(); 51 52 break; 53 default: 54 break; 55 } 56 57 } 58 //第一種方法定義一個線程 59 class FirstThread extends Thread{ 60 @Override 61 public void run() { 62 System.out.println("第一個子線程的ID---> " + String.valueOf(Thread.currentThread().getId())); 63 } 64 65 66 } 67 68 //第二種方法定義一個線程 69 class SecondThread implements Runnable{ 70 @Override 71 public void run() { 72 System.out.println("第二個子線程的ID---> " + String.valueOf(Thread.currentThread().getId())); 73 } 74 75 } 76 77 78 }
(3)java
輸出:android