eajni IT 초보사전 💦💦

[JAVA] 스레드

2022-11-15

  • 동작하고 있는 프로그램을 프로세스(Process)라고 한다. 보통 한 개의 프로세스는 한 가지의 일을 하지만, 쓰레드를 이용하면 한 프로세스 내에서 두 가지 또는 그 이상의 일을 동시에 할 수 있다.

쓰레드(thread)의 구현

Runnable 인터페이스를 구현

  • Thread 클래스를 상속하면 다른 클래스를 상속할 수 없기 때문에 보통은 Runnable 인터페이스를 구현함

      import java.util.ArrayList;
        
      public class Sample implements Runnable {
          int seq;
          public Sample(int seq) {
              this.seq = seq;
          }
        
          public void run() {
              System.out.println(this.seq+" thread start.");
              try {
                  Thread.sleep(1000);
              }catch(Exception e) {
              }
              System.out.println(this.seq+" thread end.");
          }
        
          public static void main(String[] args) {
              ArrayList<Thread> threads = new ArrayList<>();
              for(int i=0; i<10; i++) {
                  Thread t = new Thread(new Sample(i));
                  t.start();
                  threads.add(t);
              }
        
              for(int i=0; i<threads.size(); i++) {
                  Thread t = threads.get(i);
                  try {
                      t.join();
                  }catch(Exception e) {
                  }
              }
              System.out.println("main end.");
          }
      }
    

Thread 클래스를 상속


next [JAVA] OOP

Comments

Content