본문 바로가기

Java SE/Thread.setName()

Thread.setName()

/* 2개의 쓰레드가 코드와 데이터를 공유하는 상황
* 선수지식: 쓰레드의 코드공유
* Thread에 이름을 설정하고 사용하는 예
*/

class ThreadName implements Runnable{
  int i = 0;
  public void run(){
    String name = null;
    while(i<100){
      name = Thread.currentThread().getName();
      if(name.equals("t2")) {
       while(i<50) {
        try{
         Thread.sleep(50);
        }catch(InterruptedException e){}
       }
      }
      i++;
      System.out.println(name+"시작:"+i);
    try{
     Thread.sleep(50);
    }catch(InterruptedException e){}
    System.out.println(name+"끝:"+i);
    }
  }

  public static void main(String[] args) {
  ThreadName code = new ThreadName();
  Thread t1 = new Thread(code);
  Thread t2 = new Thread(code);
  t1.setName("t1");
  t2.setName("t2");

  t1.start();
  t2.start();
  }
}