Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

WON.dev

chapter21 : thread 본문

JAVA

chapter21 : thread

GAWON 2023. 5. 16. 18:36
1.1 스레드(Thread)
 - 하나의 프로세스 내부에서 독립적으로 실행되는 하나의 작업 단위.
 - ex) 작업 관리자에 실행되는 프로세스들
 - 모든 프로세스에는 최소 하나 이상의 스레드가 존재하며(main()),
   두 개 이상의 스레드를 가지면 멀티 스레드라고 한다.
 - 멀티 스레드(main() 이외의 다른 스레드)를 구현 하려면 Thread 클래스를
   상속하거나 Runnable 인터페이스를 구현해야 한다.
 - 멀티 스레드 작업 시 각 스레드끼리 정보를 주고 받을 수 있다.
 - 프로세스끼리는 정보를 주고 받을 수 없다.

1.2 스레드 생성
 - 방법
  1) Thread 클래스를 상속 받아 객체 생성
  2) Runnable 인터페이스 구현	(주로 많이 사용)
  * Thread 클래스를 상속받으면 다른 클래스를 상속받을 수 없기 때문에
    Runnable 인터페이스를 구현하는것이 일반적이다.

1.3 스레드 생성 주기

					                      Start()					        Run()
 	스레드 객체 생성(new)	→	실행 대기(Runnable)	  →		실행(Running)	   →  종료(Dead)                                    
 									              ↑						     ↓
 									                 ↖					↙
 										                  중단(Blocked)

 - Runnable 상태  : 스레드가 실행되기 전 준비 단계
 - Running 상태   : 선택된 스레드가 실행되는 단계
 - Blocked 상태   : 스레드가 작업을 완수하지 못하고 작업을 일시 중단하는 단계
Q1. Test01.java
Thread 클래스를 상속받아 2개의 쓰레드의(메인 스레드 포함)
동작 완료 시간을 출력
★System.currentTimeMillis(),
 sleep((int)(Math.random()*1000)) 이용

package org.joonzis.test;

public class Test01 extends Thread{
   @Override
   public void run() {
      
      long s_time;
      long e_time;
      
      try {
         s_time =System.currentTimeMillis();
         Thread.sleep((int)(Math.random()*1000));
         e_time =System.currentTimeMillis();
         
         System.out.println("멀티 스레드 걸린 시간 : " + (e_time-s_time));
      }catch (Exception e) {
         e.printStackTrace();
      }
   }
   
   public static void main(String[] args) {
      
      Test01 t =  new Test01();
      t.start();
      long s_time;
      long e_time;
      
      try {
         s_time =System.currentTimeMillis();
         Thread.sleep((int)(Math.random()*1000));
         e_time =System.currentTimeMillis();
         
         System.out.println("멀티 스레드 걸린 시간 : " + (e_time-s_time));
      }catch (Exception e) {
         e.printStackTrace();
      }
   
      
      
   }
}

Q2. Test02.java
멀티 스레드를 이용하여 구구단을 출력(동기화 X)
class GugudanPlay	메소드 : play(int dan)
class Gugudan		필드 : int dan, GugudanPlay gugudan
					메소드 : 생성자 , run()
class Main
 - 참조 배열 이용

package org.joonzis.test;


class GugudanPlay{
	public synchronized void play(int dan) {
		for(int i=1; i<=9; i++) {
			System.out.println(dan + "x" + i + "=" + (dan*i));
		}
	}
}
class Gugudan extends Thread{
	private int dan;
	private GugudanPlay gugudan;
	public Gugudan(int dan,GugudanPlay gugudan) {
		this.dan = dan;
		this.gugudan = gugudan;
	}
	@Override
	public void run() {
		gugudan.play(dan);
	
	}
}
public class Test02 {
	public static void main(String[] args) {
		Gugudan[]arr = new Gugudan[8];
		for(int i=0; i<arr.length; i++) {
			arr[i]= new Gugudan((i+2), new GugudanPlay());
			arr[i].start();
		}
		
		
	}
}

Q3. Test03.java
멀티 스레드를 이용하여 구구단을 출력(동기화 O)
class GugudanPlay2	메소드 : play()
class Gugudan2		필드 : int dan, GugudanPlay2 gugudan
					메소드 : 생성자 , run()
class Main
 - 참조 배열 이용, 개별 객체 이용(2가지 모두 구현)

'JAVA' 카테고리의 다른 글

chapter23 : Collection Framework  (0) 2023.05.16
chapter22 : Generic  (0) 2023.05.16
chapter20 : api  (0) 2023.05.16
chapter19 : exception  (0) 2023.05.16
chapter18 : interface  (0) 2023.05.16