JAVA

Thread class

Stater 2019. 10. 26. 09:00

Thread 

Process 

- 실행중인 프로그램

- OS로부터 메모리를 할당 받음

-> 메모리에 올라가서 할당된 상태에서 실행중인 프로그램

 

Thread

- 실제 프로그램이 수행되는 작업의 최소 단위

- 하나의 프로세스는 하나 이상의 Thread를 가지게됨

-> 실행 단위

 

프로세스

Thread를 구현하는 방법 

1. Thread를 extends 하는 방법

class Test{

	t = new Thread();
    t.start();
}

class AnyThread extends Thread{
	
    	public void run(){
        	.......
        }
}

 

2.  Runnable 인터페이스 구현

class Test{

	t = new Thread(new Anything());
    t.start();
}

class AnyThread implements Runnable{
	
    	public void run(){
        	.......
        }
}

->자바는 다중상속이 허용되지 않으므로 이미 다른 클래스를 상속할 경우 thread를 만들려면

   Runnable interface를 implements 하도록 한다.

 

두 가지 구현 예제 코드

package thread;

class MyThread extends Thread{
	 
	public void run() {
		int i ;
		
		for(i=0;i<=200;i++) {
			System.out.print(i+"\t");
			
			try {
				sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class MyThread2 implements Runnable{
	public void run() {
		int i ;
		
		for(i=0;i<=200;i++) {
			System.out.print(i+"\t");
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}


public class ThreadTest{

	public static void main(String[] args) {
		//extends를 사용한 쓰레드
		System.out.println("start");
		MyThread th1 = new MyThread();
		MyThread th2 = new MyThread();

		th1.start();
		th2.start();
		System.out.println("End");
		
		//Runnable를 사용한 쓰레드
		MyThread2 runner1 = new MyThread2();
		Thread th3 = new Thread(runner1);
		th3.start();
		
		MyThread2 runner2 = new MyThread2();
		Thread th4 = new Thread(runner2);
		th4.start();
	}

}

 

■ Multi-thread 프로그래밍

- 동시에 여러 개의 Thread가 수행되는 프로그래밍

- Thread는 각각의 작업공간(context)를 가짐

- (쓰레드가)공유 자원이 있는 경우 race condition이 발생

- critical section에 대한 동기화(synchronization)의 구현이 필요

 

조사 해볼 대상

-세마포어(크리티컬 섹션에 락을건다)-다른 쓰레드 접근불가

멀티쓰레드

 

반응형

'JAVA' 카테고리의 다른 글

멀티쓰레드 프로그래밍 multi-thread programming  (0) 2019.10.28
Thread status ( 쓰레드 상태 ) -활용  (0) 2019.10.27
입출력 클래스 및 데코레이터패턴  (0) 2019.10.25
직렬화(Serialization)  (0) 2019.10.24
보조 스트림  (0) 2019.10.23