개발 공부/JAVA

thread

공부하는개발자_ 2023. 6. 9. 12:33

 

thread : ,프로그램 내에서 실행되는 프로그램 제 흐름. 프로세스 내에 thread가 두 개라면 두 개의 코드 실행흐름이 생긴다는 것을 의미. 

multi Thread: 각자의 thread들이 하나의 독립된 프로그램처럼 동시 다발적으로 각자의 일을 수행함. 

프로세스를 10개만드는것 보다 한 프로세스 안에 10개의 Thread를 만드는 것이 좋다.

어느 thread가 cpu를 먼저 점유할 지 모름.

 

java -cp ThreadTest

1. 클래스로딩

2. 바이트코드검증

3. 0,1 재해석

4. static 변수 자동초기화

5. main-T 생성,시작

6. main -T에의한 main( ) 호출

 

 

 

 

run()가 끝나면 thread는 더 이상 효과가 없다.

 

 

 

 

 

 

 

동기화 (잠금장치) :lock걸어주는 작업 :

synchrorized( this.share객체 ) { }

share data를 사용하고 있는 다른 thread에 cpu를 빼앗기지 않도록 잠금 장치

 

thread가 가지고있는 메서드

join( ) : 다른 thread가 끝날때까지 기다림
sleep( ); 

 

wait( ); 공유객체를 사용하고 있는 thread를 일시중지. nofity()가 되어야 깨어날 수 있음.

notify( ); 공유객체를 사용하는 wait된 thread를 깨움.

 

 

 

class Share{

int balance = 0;

 

public void push(){ //balance잔액을 1씩 100번 반복증가

for(int i=0; i<100; i++) {

synchronized(this) { //balance를 쓰고있는 다른 thread에 cpu뺏기지 않는다

this.notify(); //공유객체를 사용하는 wait된 thread를 깨움

System.out.println("before push:" + balance);

balance++;

System.out.println(", after push:" + balance);

}

}

}

 

public void pop(){

for(int i=0; i<100; i--) {

synchronized(this) {

if(balance ==0) {

try {

this.wait(); //현재 공유객체를 사용하는 스레드를 일시중지한다

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.out.println("before pop:" + balance);

balance--;

System.out.println("after pop:" + balance);

}

}

}

 

 

}

 

 

class Pop extends Thread{

Share s;

 

Pop(Share s) {

this.s = s;

}

 

public void run() {

s.pop();

}

 

 

}

 

class Push extends Thread{

Share s;

 

Push(Share s){

this.s = s;

}

 

public void run() {

s.push();

}

 

 

 

}

 

public class ShareTest {

public static void main(String[] args) {

Share s = new Share();

Push ps = new Push(s); //ps.s = s;

Pop po = new Pop(s);

 

 

ps.start();

po.start();

System.out.println(s.balance);

 

}

}