搜尋此網誌

2016年8月8日 星期一

【Android】Thread

ref:
https://ptodue.gitbooks.io/book2/content/2.1.2.html
http://ptodue.blogspot.tw/search/label/Runnable
http://ptodue.blogspot.tw/search/label/runOnUiThread

實作Thread常用的使用方法有2種:

  • 繼承Thread class,再override實現run() method
  • public class MyThread extends Thread {
    public MyThread() {
    super("MyThread");
    }
    public void run() {
    System.out.println("Thread run() method executed.");
    }
    }
    //Started with a "new MyThread().start()" call
    view raw thread1.java hosted with ❤ by GitHub

    或是簡寫
    Thread t = new Thread() {
    @Override
    public void run() {
    // Block of code to execute
    // worker thread(background thread),處理需長時間或大量的運算
    System.out.println("Thread run() method executed.");
    }
    };
    t.start();
    view raw thread2.java hosted with ❤ by GitHub
  • implements Runnable(實作Runnable interface), 再override實現run() method。

  • public class MyRunnable implements Runnable {
    public void run() {
    //Code
    System.out.println("Runnable run() method executed.");
    }
    }
    //Started with a "new Thread(new MyRunnable()).start()" call
    view raw thread3.java hosted with ❤ by GitHub
    或是簡寫
    Runnable r = new Runnable() {
    @Override
    public void run() {
    // Block of code to execute
    System.out.println("Runnable run() method executed.");
    }
    };
    Thread t = new Thread(r);
    t.start();
    view raw thread4.java hosted with ❤ by GitHub

沒有留言: