티스토리 뷰
스레드 : 프로세스 내에 있으며, 운영체제가 CPU에 실행하도록 스케줄하는 기본 단위
Thread안에 Runnable 인터페이스가 참조 변수로 들어가있다
Runnable은 run( ) 메소드 하나만 정의되어 있다
1. Thread 클래스 사용
기본 형태
class 클래스 이름 extends Thread {
public void run( );
// 구현
}
선언한 클래스 안에서 run( ) 메소드를 사용하기 위해 Thread 클래스를 상속 받아 씀
public class ThreadEx extends Thread { //Thread 클래스 상속
public void run() {
while(true) {
System.out.println("스레드 예시");
}
}
}
2. Runnable 인터페이스 사용
기본 형태
class A(클래스 이름) extents 부모 클래스 implemets Runnable {
public void run( );
// 구현
public static void main( String[ ] args ){
//메인 함수
}
}
Runnable 인터페이스를 상속 받은 클래스는 스레드를 돌리기 위한 함수를 구현만 한 것
Thread를 실행시키기 위한 방법
1. 대부분, 참조 변수 타입을 Runnable로 동적 바인딩을 해서 객체를 생성한다
2. 선언한 참조 변수를 Thread 클래스 생성자에게 보내서, Thread의 객체를 생성한다
#상속을 통해서 run( )을 오버라이딩 하지 않고도 외부로부터 제공받아서 사용할 수 있다
#동적 바인딩 : 프로그램이 실행이 되야 메모리가 얼마만큼 할당 되는지 알 수 있다
Runnable r = new ThreadEx();
Thread t = new Thread(r);
#위의 선언를 합친 것
Thread t = new Thread(new Runnable());
경우
1. Runnable 인터페이스를 상속 받은 클래스 안에서 메인 함수를 사용하는 경우
- 클래스 A를 메인 함수에서 돌리기 위해서는 Thread 클래스의 객체를 생성해야 한다
public class ThreadEx implements Runnable {
public void run() {
while(true) {
System.out.println("스레드 예시");
}
}
public static void main(String[] args) {
Runnable r = new ThreadEx();
Thread t = new Thread(r);
}
}
2. 다른 클래스 내에서 메인 함수를 구현한 경우
- 인터페이스를 구현한 객체를 다른 클래스에서 생성해야 한다
public class RunnableThread implements Runnable {
public void run() {
while(true) {
System.out.println("스레드 예시");
}
}
}
public class ThreadEx{
public static void main(String[] args) {
Runnable r = new RunnableThread();
Thread t = new Thread(r);
//구현
}
}
싱글 스레드
- extends Thread
public class SingleThreadEx extends Thread {
private int[] temp;
public SingleThreadEx(String threadname) {
super(threadname); //Thread의 생성자 호출
temp = new int[10];
for (int start = 0; start < temp.length; start++) {
temp[start] = start;
}
}
public void run() {
for (int start : temp) {
try { //예외처리
Thread.sleep(1000); //1초
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.print("스레드 이름 : " + Thread.currentThread().getName());
System.out.println(" temp value : " + start);
}
}
public static void main(String[] args) {
SingleThreadEx st = new SingleThreadEx("superman");
st.start();
}
}
- implements Runnable
public class SingleThreadEx implements Runnable{
private int[] temp;
public SingleThreadEx() {
//super(threadname); //object를 불러옴
temp = new int[10];
for (int start = 0; start < temp.length; start++) {
temp[start] = start;
}
}
public void run() {
for (int start : temp) {
try {
Thread.sleep(1000); //1초
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.print("스레드 이름 : " + Thread.currentThread().getName());
System.out.println(" temp value : " + start);
}
}
public static void main(String[] args) {
Runnable r = new SingleThreadEx();
Thread t = new Thread(r, "superman"); //Thread의 이름을 주는 생성자
t.setName("superman"); //Thread의 이름을 주는 함수
t.start();
}
}
- join( ) : 해당 Thread가 종료 될 때 까지 기다리게 만듬
class MyRunnableTwo implements Runnable {
public void run() {
System.out.println("run");
first();
}
public void first() {
System.out.println("first");
second();
}
public void second() {
System.out.println("second");
}
}
public class JoinEx {
public static void main(String[] args) throws InterruptedException{
System.out.println(Thread.currentThread().getName() + " start");
Runnable r = new MyRunnableTwo();
Thread myThread = new Thread(r);
myThread.start();
// try { //join은 예외처리를 해줘야 한다
myThread.join();
// } catch (InterruptedException ie) {
// ie.printStackTrace();
// }
System.out.println(Thread.currentThread().getName() + " end");
}
}
멀티 스레드
- 하나의 프로세스에서 여러 개의 스데드가 병행적으로 처리되는 것
- 동시에 일어나는것 같지만, 실질적으로 여러개의 스레드가 병렬로 실행되는 것
'LANGUAGE > JAVA' 카테고리의 다른 글
[JAVA] 문자열 계산기 (0) | 2018.03.21 |
---|---|
[JAVA] 성적 처리 (0) | 2018.03.20 |
[JAVA] ARRAY - 배열 (0) | 2018.03.20 |
[JAVA] THIS (0) | 2018.03.20 |
[JAVA] BASIC THINGS (0) | 2018.03.19 |