Programming/JAVA
Thread (쓰레드)
dev?
2022. 5. 17. 13:55
반응형
프로세스(process)
- 실행 중인 프로그램(program)
(사용자가 작성한 프로그램이 운영체제에 의해 메모리 공간을 할당받아 실행 중인 것)
- 데이터와 메모리 등의 자원 그리고 스레드로 구성
스레드(thread)
- 프로세스(process) 내에서 실제로 작업을 수행하는 주체
- 모든 프로세스에는 한 개 이상의 스레드가 존재하여 작업을 수행한다.
두 개 이상의 스레드를 가지는 프로세스를 멀티스레드 프로세스(multi-threaded process)라고 한다.
- 'Thread 클래스를 상속'
'Runnable 인터페이스 구현' 2가지 방법이 있다.
// Thread를 상속받음 - run 메서드를 구현해야 함
public class Sample extends Thread {
public void run(){
// thread로 실행되는 내용
}
}
// thread 실행 메서드
thread명.start();
사용 예제
1) Thread 클래스를 상속
class Exam1 extends Thread {
// thread로 동작되는 함수
@Override
public void run() {
System.out.println("Test thread 1");
for (int i = 0; i <= 58; i++) {
System.out.println((char) (i + 65));
}
}
}
public class
Main {
public static void main(String[] args) {
Exam1 exam1 = new Exam1();
System.out.println("run 함수 전");
exam1.start(); // thread run 함수 동작
// main thread로서 동작되는 명령어
for (int i = 0; i <= 50; i++) {
System.out.println(i);
}
System.out.println("-- 끝 -- ");
}
}
2) Runnable 인터페이스 구현
class ThreadExam2 implements Runnable {
// thread로서 동작될 함수
@Override
public void run() {
System.out.println("Test thread 2");
for (int i = 0; i <= 60; i++) {
System.out.println((char) (i + 65));
}
}
}
public class Exam2 {
public static void main(String[] args) {
System.out.println("run()함수 전");
ThreadExam2 threadExam2 = new ThreadExam2();
Thread thread = new Thread(threadExam2);
thread.start(); // run()함수로 thread 실행
// main thread로서 동작되는 명령어
for (int i = 0; i <= 500; i++) {
System.out.println(i);
}
System.out.println("-- 끝 --");
}
}
http://www.tcpschool.com/java/java_thread_concept
반응형