start buttonを押すとThreadが背景で執行される方法。
#手法1. extends Thread class
MainActivity.java
//This method will be onClick method of a button
public void startThread(View view){
MyThread myThread=new MyThread(10);
myThread.start();
}
//create a custom thread
public class MyThread extends Thread{
//defining second externally
int seconds;
//create a constructor and take parameter of seconds
public MyThread(int seconds){
this.seconds=seconds;
}
//Override run method
@Override
public void run() {
for(int i=0;i<seconds;i++){
Log.d(TAG, "startThread:" + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
startを押すと背景でThreadが執行されながらも、UIは凍結せず相変わらず使用可能です
#手法2. implements Runnable interface
MainActivity.java
//This method will be onClick method of a button
public void startThread(View view){
Run run=new Run(10);
new Thread(run).start();
}
//defining custom runnable class
public class Run implements Runnable{
int seconds;
//create constructor
public Run(int seconds){
this.seconds=seconds;
}
public void run() {
for(int i=0;i<seconds;i++){
Log.d(TAG, "startThread:" + i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
二つの手法の結果は同じです。以上です。