Android Thread編程

最簡單的一個線程應用的例子:

public class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainActivity);

new Thread(){
@Override
public void run(){
System.out.println(“Thread is starting…”);
}
}.start();
}
}

使用Runnable的例子:

Runnable runnable = new Runnable() {
@Override
public void run(){
System.out.println(“Runnable is starting…”);
}
};

public class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainActivity);

new Thread(runnable).start();
}
}

常見的Multi-Thread的用法:

public class TestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainActivity);

MyTestThread myTestThread1 = new MyTestThread();

MyTestThread myTestThread2= new MyTestThread();
MyTestThread myTestThread3 = new MyTestThread();

myTestThread1.start();
myTestThread2.start();
myTestThread3.start();

}
}

class MyTestThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ” is running…”);

}
}

運行結果:

I/System.out(672): Thread-10 is running…

I/System.out(672): Thread-11 is running…

I/System.out(672): Thread-12 is running…

以上代碼還可以使用實例化Multi-Thread的用法:

MyTestThread myTestThread = new MyTestThread();

new Thread(myTestThread, “My Thread 1”).start();
new Thread(myTestThread, “My Thread 2”).start();
new Thread(myTestThread, “My Thread 3”).start();

運行結果:

I/System.out(672): My Thread 1 is running…

I/System.out(672): My Thread 2 is running…

I/System.out(672): My Thread 3 is running…

線程休眠:sleep (待續)

線程優先級:priority (待續)

線程讓步(調度):yield (待續)

後臺線程:daemon (待續)

使用執行器:Executer (待續)

定義任務:Runnable (待續)

發佈留言