고급JAVA 7강 - 쓰레드

Whatever·2021년 11월 5일
0

고급 JAVA

목록 보기
7/32

쓰레드
1. 프로세스와 쓰레드
프로세스란 '실행 중인 프로그램'
프로그램을 실행하면 OS로부터 실행에 필요한 자원(메모리)을 할당받아 프로세스가 된다.

그냥 프로그램 - 실행되기 전 상태
프로세스 - 프로그램이 실행되고있는 상태
쓰레드를 하나만 사용 - 싱글쓰레드
한 프로그램에서 여러 쓰레드를 사용 - 멀티쓰레드

1.2 멀티프로세스 vs 멀티쓰레드

멀티프로세스 - 하나의 운영체제 내에서 여러 개의 프로그램이 실행중인 것
멀티쓰레드 - 한 프로그램 내에서 여러 쓰레드에 각각의 일을 하게 하는 것

1.3 멀티쓰레드의 장단점
장점

  • 자원의 효율적 사용
  • 사용자에 대한 응답성 향상 =>처리속도가 빠름
  • 작업이 분리되어 코드가 간결해진다.

단점

  • 동기화에 주의
  • 교착상태가 발생하지 않도록 주의
  • 각 쓰레드가 효율적으로 고르게 실행될 수 있게 해야한다.

1.4 쓰레드의 구현과 실행

1.Thread 클래스를 상속
2.Runnable 인터페이스를 구현

// 멀티 쓰레드 프로그램

	// Thread를 사용하는 방법 - 클래스와 인터페이스가 있는 이유 : 추가로 상속받을 경우를 대비해서
	
	// 방법1
	// ==> Thread클래스를 상속한 class를 작성한 후 이 class의 인스턴스를 생성한 후 
	// 이 인스턴스의 start()메서드를 호출해서 실행한다. 
	MyThread1 th1 = new MyThread1(); // 인스턴스 생성하기
	th1.start(); // 쓰레드 실행하기

	// 방법2
	// ==> - Runnable인터페이스를 구현한 class를 작성한다.
	//	   - 이 class의 인스턴스를 생성한다.	
	//     - Thread클래스의 인스턴스를 생성할 때 생성자의 인수값으로 이 class의 인스턴스를 넣어준다.
	//     - Thread클래스의 인스턴스의 start()메서드를 호출해서 실행한다.
	//MyRunner1 r = new MyRunner1();
	//Thread th2 = new Thread(r); //Thread클래스의 인스턴스 생성 
               - 인수값으로 Runnable을 구현한 클래스의 인스턴스를 넣음. 
	//th2.start();
	//Thread th2 = new Thread(new MyRunner1()); //이것도 가능
	th2.start();
	
	// 방법3 
	// ==> 익명구현체를 이용하는 방법 - 이름없이 구현할 수 있다.
	Thread th3 = new Thread(new Runnable() {
		
		@Override
		public void run() {
			for(int i = 1; i <= 200; i++) {
				System.out.print("@");
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO: handle exception
				}
			}
		}
	});
	th3.start();
	
	System.out.println("main()메서드 끝...");
}
//start가 쓰레드를 자동으로 만들어주고 그 쓰레드 안에서 run메서드를 불러오는 것이 start()메서드의 할일

}

//방법1 - Thread클래스 상속하기
class MyThread1 extends Thread{
    @Override
    public void run() {
        // 이 run()메서드 안에는 쓰레드에서 처리할 내용을 기술한다.
        for(int i = 1; i <= 200; i++) {
            System.out.print("*");
		
		try {
			// Thread.sleep(시간); ==> 주어진 '시간'동안 잠시 멈춘다.
			// '시간'은 밀리세컨드 단위를 사용한다.
			//  즉, 1000은 1초를 의미한다.
			Thread.sleep(100);
		}catch(InterruptedException e) {
			
		}
	}
}

}

//방법2 - Runnable인터페이스 구현하기
class MyRunner1 implements Runnable{
@Override
public void run() {
for(int i = 1; i <= 200; i++) {
System.out.print("$");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}

}

멀티쓰레드에서 한 가지 프로그램이라도 실행중이면 실행중인 것
=> 모든 쓰레드가 끝나야 프로그램이 종료되는 것

1.7 쓰레드의 우선순위
우선순위를 정해도 의미가 없다. => OS스케쥴러에 의해 결정되기 때문

1.9 데몬 쓰레드(daemon thread)

  • 일반 쓰레드의 작업을 돕는 보조적인 역할을 수행
  • 일반 쓰레드가 모두 종료되면 자동적으로 종료된다.
  • 가비지 컬렉터, 자동저장, 화면자동갱신 등에 사용된다.
  • 무한루프와 조건문을 이용해서 실행 후 대기하다가 특정조건이 만족되면
    작업을 수행하고 다시 대기하도록 작성한다.

사용자로부터 데이터 입력받기

	String str = JOptionPane.showInputDialog("아무거나 입력하세요");
	System.out.println("입력값 : " + str);
    
    

// 쓰레드가 수행되는 시간 체크하기

	Thread th = new Thread(new MyRunnable2());
	
	
	// 1970년 1월 1일 0시0분0초(표준시간)로부터 경과한 시간을 밀리세컨드 단위(1/1000초)로 반환한다.
	long startTime = System.currentTimeMillis();
	
	th.start(); //쓰레드 환경을 만들고 실행시키고 끝남
	
	try {
		th.join(); //현재 실행중인 쓰레드에서 대상이 되는 쓰레드(여기서는 변수 th)가 종료될 때까지 기다린다.
	} catch (Exception e) {
		// TODO: handle exception
	}
	
	long endTime = System.currentTimeMillis();
	
	System.out.println("경과 시간 : " + (endTime - startTime));
	
	
}

}

class MyRunnable2 implements Runnable{

@Override
public void run() {
	long sum = 0L;
	for(long i = 1; i <= 1000_000_000L; i++) { //자바에서는 자릿수를 나타낼 때 쉼표(,)대신 _를 나타내게 해줌
		sum += i;
	}
	System.out.println("합계 : " + sum);
}

}

/
1 ~ 20억까지의 합계를 구하는 프로그램 작성하기
1) 이 작업을 하나의 쓰레드가 단독으로 처리하는 경우와
2) 여러개의 쓰레드가 협력해서 처리할 대의 경과시간을 비교해 본다.
/
public class ThreadTest04 {

public static void main(String[] args) {
	// 단독으로 처리할 쓰레드 생성
	SumTread sm = new SumTread(1L, 2_000_000_000L);
	
	// 협력해서 처리할 쓰레드 생성(4개의 쓰레드 객체 생성)
	SumTread[] smArr = new SumTread[] {
			new SumTread(1L, 500_000_000L),
			new SumTread(500_000_001L, 1_000_000_000L),
			new SumTread(1_000_000_001L, 1_500_000_000L),
			new SumTread(1_500_000_001L, 2_000_000_000L)
	};
	
	//단독으로 처리하기
	sm.start();
	
	long startTime = System.currentTimeMillis();
	try {
		sm.join();
	} catch (InterruptedException e) {
		// TODO: handle exception
	}
	long endTime = System.currentTimeMillis();
	System.out.println("단독으로 처리할 때의 경과 시간 : " + 
			(endTime - startTime));
	System.out.println();
	System.out.println();
	
	//여러 쓰레드가 협력해서 처리하는 경우
	startTime = System.currentTimeMillis();
	
	for(SumTread s : smArr) {
		s.start();
	}
	
	for(int i = 0; i < smArr.length; i++) {
		try {
			smArr[i].join();
		} catch (InterruptedException e) {
			// TODO: handle exception
		}
	}
	endTime = System.currentTimeMillis();
	
	System.out.println("협력해서 처리한 경과 시간 : " 
			+ (endTime - startTime));
}

}

class SumTread extends Thread{
//합계를 구할 영역의 시작값과 종료값이 저장될 변수 선언
private long min, max;

public SumTread(long min, long max) {
	this.min = min;
	this.max = max;
}

@Override
public void run() {
	long sum = 0L;
	
	for(long i = min; i <= max; i++) {
		sum += i;
	}
	
	System.out.println("합계 : " + sum);
}

}

public static void main(String[] args) {

	Thread th1 = new UpperThread();
	Thread th2 = new LowerThread();
	
	//우선 순위 변경하기 - start()메서드 호출 전에 설정한다.
	th1.setPriority(6);
	th1.setPriority(8);
	
	
	System.out.println("th1의 우선순위 : " + th1.getPriority());
	System.out.println("th2의 우선순위 : " + th2.getPriority());
	
	th1.start();
	th2.start();
}

}

// 대문자를 출력하는 쓰레드
class UpperThread extends Thread{
@Override
public void run() {
for(char c = 'A'; c <= 'Z'; c++) {
System.out.println(c);

		//아무작업도 안하는 반복문 (시간 때우기용)
		for(long i = 1; i < 1_500_000_000L; i++) { }
	}
}

}

//소문자를 출력하는 쓰레드
class LowerThread extends Thread{
@Override
public void run() {
for(char c = 'a'; c <= 'z'; c++) {
System.out.println(c);

		//아무작업도 안하는 반복문 (시간 때우기용)
		for(long i = 1; i < 1_500_000_000L; i++) { }
	}
}

}

public static void main(String[] args) {
AutoSaveThread autoSave = new AutoSaveThread();

	// 데몬 쓰레드로 설정하기 => 반드시 start()메서드 호출 전에 설정한다.
	autoSave.setDaemon(true);
	
	autoSave.start();
	
	try {
		for(int i = 1; i <= 20; i++) {
			System.out.println(i);
			Thread.sleep(1000);
		}
	} catch (InterruptedException e) {
		// TODO: handle exception
	}
	System.out.println("main 쓰레드 작업 끝");

}

}

// 자동 저장하는 쓰레드 작성(3초에 한번씩 자동 저장하기)
class AutoSaveThread extends Thread{
// 작업 내용을 저장하는 메서드
public void save() {
System.out.println("작업 내용을 저장합니다.");
}

@Override
public void run() {
	while(true) {
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO: handle exception
		}
		save();
	}
}

}

public static void main(String[] args) {

	Thread th1 = new DataInput();
	Thread th2 = new CountDown();
	
	th1.start();
	th2.start();
}

}

// 데이터를 입력하는 쓰레드
class DataInput extends Thread{
// 입력 여부를 확인하기 위한 변수 선언
// 쓰레드에서 공통으로 사용할 변수
public static boolean inputCheck = false;
@Override
public void run() {
String str = JOptionPane.showInputDialog("아무거나 입력하세요");
inputCheck = true; // 입력이 완료되면 true로 변경
System.out.println("입력값 : " + str);
}
}

// 카운트 다운을 진행하는 쓰레드
class CountDown extends Thread{
@Override
public void run() {
for(int i = 10; i >= 1; i--) {
System.out.println(i);
//입력이 완료되었는지 여부를 검사해서 입력이 완료되면 쓰레드를 종료시킨다.
if(DataInput.inputCheck) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO: handle exception
}
}
System.out.println("10초가 지났습니다. 프로그램을 종료합니다.");
System.exit(0);
}

}

0개의 댓글