Back-end/Java, Kotlin

Thread에 대한 것들

philo0407 2021. 7. 14. 09:55

쓰레드 생성은 아래와 같다. 방식은 크게 두가지이다.

class ThreadSapmle extends Thread {
  @Override
  public void run() {
    StringBuffer sb = new StringBuffer("Running ThreadSample ");
  }
}

public Class Main {
    public static void main(String[] args) {
        ThreadSample th = new ThreadSample();
        ThreadSample th2 = new ThreadSample();
        th.start();
        th2.start();
    }
}

 

 

class RunnableSapmle implements Runnable {
  @Override
  public void run() {
    StringBuffer sb = new StringBuffer("Running RunnableSapmle ");
  }
}

public Class Main {
    public static void main(String[] args) {
        Runnable rn = new RunnableSampe();
        Runnable rn2 = new RunnableSampe();
        ThreadSample th = new ThreadSample(rn);
        ThreadSample th2 = new ThreadSample(rn2);
        th.start();
        th2.start();
    }
}

synchronized 를 안했을 때 발생하는 대표격 예제

실패한 예제를 먼저 보겠다.

 

 

public class ThreadMain {

  public static final int ThreadGenNum = 2;
  public static final int RetryNum = 5;

  public static void main(String[] args) {
    for (int i = 0; i < RetryNum; i++) {
      runThread();
    }
  }

  public static void runThread() {
    ArithmeticThread[] th = new ArithmeticThread[ThreadGenNum];
    CmmMemory cmmMemory = new CmmMemory();
    for (int i = 0; i < ThreadGenNum; i++) {
      th[i] = new ArithmeticThread();
      th[i].setThreadGenNum(ThreadGenNum);
      th[i].setCmmMemory(cmmMemory);
      th[i].start();
    }
    for (int i = 0; i < ThreadGenNum; i++) {
      try {
        th[i].join();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("cmmMemory.cnt = " + cmmMemory.getCnt());
  }
}

 

성공한 것은 위쪽이다.