JAVA 스레드

O0·2022년 6월 12일
0

JAVA

목록 보기
3/4
post-thumbnail

스레드


1.프로세스

  • 실행 중인 프로그램
  • 사용자가 작성한 프로그램이 운영체제에 의해 메모리 공간을 할당받아 실행 중인 것
  • 프로세스 = 데이터 + 메모리 + 자원 + 스레드 등 으로 구성
  1. 스레드
  • 프로세스 내에서 실제로 작업을 수행하는 주체
  • 모든 프로세스는 한 개 이상의 스레드가 존재하여 작업을 수행
  • 두 개 이상의 스레드를 가지는 프로세스를 멀티스레드 프로세스라고 한다.
  1. 스레드의 생성과 실행
  • 스레드 생성 방법
    1) Runnable 인터페이스를 구현하는 방법 (선호)
    2) Thread 클래스를 상속받는 방법
  • 두 방법 모두 스레드를 통해 작업하고 싶은 내용을 run() 메소드에 작성하면 된다.
package main;

public class MainClass {
	public static void main(String[] args) {
		ThreadWithClass thread1 = new ThreadWithClass();		//쓰레드 클래스를 상속받는 방법
		Thread thread2 = new Thread(new ThreadWithRunnable());  //Runnable 인터페이스를 구현하는 방법
		
		thread1.start();
		thread2.start();
	}
}

class ThreadWithClass extends Thread{
	public void run() {
		for(int i=0; i<5; i++) {
			System.out.println(getName()+" : 1"); //현재 실행 중인 스레드의 이름을 반환.
			try {
				Thread.sleep(10); //0.01초간 스레드를 멈춤
			} catch(InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class ThreadWithRunnable implements Runnable {
	public void run() {
		for(int i=0; i<5; i++) {
			System.out.println(Thread.currentThread().getName()); //현재 실행 중인 스레드 이름 반환
			try {
				Thread.sleep(10);
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}

profile
O0

0개의 댓글