Louie NRT Story

[안드로이드] Thread와 Runnable 본문

전기차충전기

[안드로이드] Thread와 Runnable

hyeok0724.kim@gmail.com 2021. 11. 23. 21:24
반응형

작성일: 21년 11월 23일

 

Index

1. Thread와 Runnable 코드

2. Thread 클래스 확인해보기

 

 

1. Thread와 Runnable 코드

 - Thread와 Runnable의 차이점은 상속이냐 인터페이스냐의 차이임

 - Runnable을 사용하는 것을 추천하는데 인터페이스이기 때문에 재사용성이 좋기 때문임

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ThreadEx1 ex1 = new ThreadEx1();
        ex1.start();

        ThreadEx2 ex2 = new ThreadEx2();
        Thread t1 = new Thread(ex2);
        t1.start();
    }

    class ThreadEx1 extends Thread{
        public void run(){
            while(true){
                Log.d("ThreadEx1", "Thread 1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class ThreadEx2 implements Runnable{
        public void run(){
            while(true){
                Log.d("ThreadEx1", "Runable 1");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

 - 로그를 보면 모두가 예상한 로그가 나오고 있음을 알 수 있음

 

2. Thread 클래스 확인해보기

 - Thread가 Runnable 인터페이스를 이용함

 

Reference:

https://dev-troh.tistory.com/47

 

반응형
Comments