JAVA

멀티쓰레드 프로그래밍 multi-thread programming

Stater 2019. 10. 29. 09:00

멀티쓰레드 프로그래밍

-Dead lock

프로세스가 자원을 할당 받지 못해, 다음 처리를 하지 못하는 상태 = 교착상태

발생이유: 시스템의 한정된 자원을 영러곳에서 사용하려고 할 때 발생

 

wait(): 리소스가 더이상 유효하지 않은 경우 리소스가 사용 가능 할 때 까지 위해 thread를 non-runnable 상태로 전환

 

notify() : wait()하고 있는 thread 중 한 thread를 runnable한 상태로 깨움

 

notifyAll():wait()하고 있는 모든 thread가 runnable한 상태가 되도록 함

notify()보다 notifyAll()를 사용하기를 권장

특정 thread가 통지를 받도록 제어 할 수 없으므로 모두 깨운 후 scheduler에 CPU를 점유하는 것이 좀 더 공평 하기

때문

 

한정된 자원을 가지고 처리하는 방법의 예제 소스코드

package thread;

import java.util.ArrayList;

class FastLibrary{
	public ArrayList<String> books = new ArrayList<String>();
	
	public FastLibrary() {
		books.add("태백산백1");
		books.add("태백산백2");
		books.add("태백산백3");
//		books.add("태백산백4");
//		books.add("태백산백5");
//		books.add("태백산백6");
	}
	
	public synchronized String lendBook() throws InterruptedException{
		
		Thread t = Thread.currentThread();
		while(books.size()==0) {
			System.out.println("wait start");
			//웨잇처리
			wait();
			System.out.println("wait end");
		}
//			return null;//한정된자원을 처리 		
		String title = books.remove(0);
		System.out.println(t.getName()+":"+title+"lend");
		return title;
	}
	
	public synchronized void returnBook(String title) {
		Thread t = Thread.currentThread();
		books.add(title);
		//책이오면 알리는 notifyAll()
		//notifyAll()을 사용할 경우에는 if문이 아닌  while문을 사용-> 모두 다 꺠어나고 신호를 주기 떄문에 제어하기위해서 사용
		notifyAll();
		System.out.println(t.getName()+":"+title+"return");
		
	}
}

class Student extends Thread{
	public void run() {

		
		try {
			String title = LibraryMain.library.lendBook();
			if(title==null)return;
			sleep(5000);
			LibraryMain.library.returnBook(title);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}
}

public class LibraryMain {

	public static FastLibrary library = new FastLibrary();
	public static void main(String[] args) {
		Student std1 = new Student();
		Student std2 = new Student();
		Student std3 = new Student();
		Student std4 = new Student();
		Student std5 = new Student();
		Student std6 = new Student();
		
		
		std1.start();
		std2.start();
		std3.start();
		std4.start();
		std5.start();
		std6.start();
		


	}

}
반응형

'JAVA' 카테고리의 다른 글

Chpter01. 변수  (0) 2023.03.07
Chapter01. 변수  (0) 2023.02.23
멀티쓰레드 프로그래밍 multi-thread programming  (0) 2019.10.28
Thread status ( 쓰레드 상태 ) -활용  (0) 2019.10.27
Thread class  (0) 2019.10.26