멀티스래드 프로그래밍 ?

동시에 여래개의 스레드가 수행되는 프로그램ㅇ

스레드는 각각의 작업공간(context)를 가짐

공유 자원이 있는 경우 race condition 이 발생

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

 

인터럽트(interrupt) 메서드

다른 스레드에 예외 발새시키는 interrupt를 보냄

thread가 join(),sleep().wait() 메서드 에 의해 블럭킹 되었다면 interrupt에 의해 다시 

runnable 상태가 될수 있음 

package Test01;


class InterruptTest extends Thread{
	public void run() {
		int i;
		for(i=0;i<100;i++) {
			System.out.print(i);
		}
		
		try {
			sleep(5000);
		} catch (InterruptedException e) {
			// TODO: handle exception
			System.out.println();
			System.out.print(e);
			System.out.print(" wake!!");
		}
	}
	
}


public class Main {

	
	
	public static void main(String [] args) {
	
		InterruptTest it=new InterruptTest();
		
		it.start();
		it.interrupt();
		
      
	}
	
	
	
}

Thread 종료하기

무한 반복하는 스레드가 종료될수 있도록 run()메서드 내의 while문을 활용 

Thread.stop()은 사용하지 않음 ->boolean flag를 이용하여 종료 

 

package Test01;

import java.io.IOException;

class TerminatedTest extends Thread{
	
	private boolean flag=false;
	
	public TerminatedTest(String name) {
		super(name);
	}
	
	int i;
	public void run() {
		while(!flag) {
			
			
			try {
				sleep(100);
			} catch (InterruptedException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			
			
			
		}
		System.out.println(getName()+" end");
	}
	public void setFlag(boolean flag) {
		this.flag=flag;
	}
	
}


public class Main {

	
	
	public static void main(String [] args) throws IOException {
	
		TerminatedTest threadA=new TerminatedTest("A");
		TerminatedTest threadB=new TerminatedTest("B");
		threadA.start();
		threadB.start();
		int in;
		while(true) {
			in=System.in.read();//console 입력
			if(in =='A') {
				threadA.setFlag(true);
			}else if(in =='B') {
				threadB.setFlag(true);
			}else if(in =='M') {
				threadA.setFlag(true);
				threadB.setFlag(true);
				break;
			}else {
				//System.out.println("try again");
			}
			
			
		}
		
		System.out.println("main end");
	}
	
	
	
}

'프로그래밍언어 > JAVA' 카테고리의 다른 글

<JAVA>멀티스래드 프로그래밍-3  (0) 2020.12.13
<JAVA>멀티 스레드 프로그래밍 -2  (0) 2020.12.13
<JAVA>Thread  (0) 2020.12.13
<JAVA>데코레이터 패턴  (0) 2020.12.13
<JAVA>몇가지 추가 입출력 클래스  (0) 2020.12.13

+ Recent posts