안드로이드/Java

[Java] Thread(1)

만능성구 2020. 4. 26. 17:49
728x90

Thread란

하나의 Process 내부에서 독립적으로 실행되는 하나의 작업 단위.

Multi - Thread란

여러 Thread를 동시에 실행시키는 응용프로그램 작성 기법

기본적으로 하나의 Process에 하나의 Thread가 존재

여러 Processes가 할 수 있는 일을 한 번에 사용할 수 있도록 한 Process에서 Thread로 분활

동시에 여러 개의 일을 해야 할 때 사용!


Threads 특징

  • The ability to do multiple things at once within the same application
    • Finer granularity of concurrency
  • Lightweitght
    • Easy to create and destroy
  • Shared address-space
    • Can share memory variables directly
    • May require more cmplex synchronization logic because of shared address space

Advantages of threads…

  • Use multiple processors
    • Code is partitioned in order to be able to use n processors at once
      • This is not easy to do! But Moore’s Law may force us in this direction
  • Hide network/disk latency 네트워크 disk 대기시간 줄이기
    • While one thread is waiting for something, run the others
    • Dramatic improvements even with a single CPU
      • Need to efficiently block the connections that are waiting, while doing useful work with the data that has arrived
    • Writing good network codes relies on concurrency!
  • Keeping the GUI responsive
    • Separate worker threads from GUI thread

Thread 작성법

  1. Thread Class 상속

    class Thread1 extends Thread{
        public void run(){
            ...code
           }
    }

    상속 받은 클래스의 객체를 생성하고 start메서드 호출

...//실행
Thread1 t1 = new Thread1();
t1.start();
...

 


  1. Runnable interface

    class Thread2 implements Runnable{
        public void run(){
        ...code
        }
    }

    Thread 클래스 생성하고 생성자에 인터페이스를 구현한 클래스의 객체를 넣어준다. 그 이후 start메서드 호출

...//실행
Thread2 t2 = new Thread1();
Thread t = new Thread(t2);
t.start();
...

 

728x90