JAVA Programming

[85] Thread 멀티 기타메소드CurrentThread() , wait() , join() ,

꾸준히개발하자 2020. 8. 3. 19:07

 Thread의 여러가지 메소드 활용

Runnable 한 상태가 되야지 CPU를 점유할수있다.

스케쥴러가 CPU를 배분해주게된다. 스레드가 돌다가 Dead 끝이나면

Sleep(시간) , wait() ,

1000을 넣으면 천분의 1초로 Runnable 상태로 빠진다.

NotRunnable 상태가 되야 CPU를 점유할수없다.

Wait 은 동기화할 때 얘기할 것 스레들리소스를 기다릴떄 쓰인다.

Join 두개의 스레드가 동시에 돌아가면 한스레드가 다른 스레드에게 join 을 걸면

다른스레드가 끝날떄까지 join건 스레드가 Not Runnable 상태로 빠진다.  

 

다시 돌아오게 하려면

Sleep(시간) -> 시간이 지나면 돌아온다.

wait() 에서 notify() 를 걸면 돌아오게 된다.

Join() 에서 other 스레드가 끝나게 되면 runnable 상태로 오게 된다.

 

Not Runnable 에 인터럽트 이셉션을 날리면 인터럽트에 의해서 이셉션에 빠지고

끝이난다.

 

CurrentThread() static 메소드 인데.

틀벽히 priority 를 지정하지 않으면 기본값은 5가 된다.

 

 

package thread;

class MyThread2 implements Runnable {

	@Override
	public void run() {
		try {
			Thread.sleep(100);  // static 메서드인 Thread를 바로 쓸수 있다.
		} catch (InterruptedException e) { 
			e.printStackTrace();
		}
	}
}
public class ThreadRunnable {

	public static void main(String[] args) {
		System.out.println("Strat");
		Thread t = Thread.currentThread(); // static 메소드 , 현재 돌고있는 스레드를 가져옴
		System.out.println(t);	
		System.out.println("end"); // 메인스레드가 먼저 종료 한다. 
	}
}

 

 

CurrentThread() 메소드는 현재 스레드를 보여준다.

Join (Join을 건 스레드가 NotRunnable 상태가 된다. )

다른스레드의 결과가 다른스레드의 결과가 필요한 경우

join() 메소드는 join을 건 스레드가 NotRunnable 상태가 된다.

 

Join 을 걸지않으면 동시에 실행하게 되서 0이 나온다.

 

package thread;

public class JoinTest extends Thread {

	int start;
	int end;
	int total;
	
	public JoinTest(int start , int end) {
		this.start = start;
		this.end = end;
	}
	public void run() {
		int i;
		for(i = start; i <= end; i++) {
			total += i;
		}
	}
	public static void main(String[] args) {	
		
		JoinTest jt1 = new JoinTest(1,50); // 1부터 50까지 더한다.
		JoinTest jt2 = new JoinTest(51,100); // 1부터 50까지 더한다.
	
		jt1.start();
		jt2.start();
		
		// 동시에 하지 못하게 Join을 걸어야 한다.
		try {
			jt1.join();
			jt2.join();
		} catch (InterruptedException e) {
			e.printStackTrace(); // 이터럽트 이셉션을 쓰면 빠지게 된다. 
		}	
		// 두개가 돌림으로써 가져오는 토탈
		int total = jt1.total + jt2.total;
		System.out.println( " jt1.total = " + jt1.total );
		System.out.println( " jt2.total = " + jt2.total );
		System.out.println(total);
	}
}

 

jt1 스레드가 끝나고 나서 jt2 스레드가 시작하게되서

total 를 구할수있다.