LoginSignup
0
1

More than 3 years have passed since last update.

Background Thread

Posted at

start buttonを押すとThreadが背景で執行される方法。
image.png

手法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は凍結せず相変わらず使用可能です
image.png

手法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();
                }
            }

        }
    }

二つの手法の結果は同じです。以上です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1