Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

wait(), notify() 메서드 활용한 동기화 프로그래밍 본문

Java/다양한 기능

wait(), notify() 메서드 활용한 동기화 프로그래밍

Seung__ 2021. 11. 3. 23:19

1. wait(), notify() 


  • 리소스가 어떤 조건에서 더 이상 유효하지 않은 경우 리소스를 기다리기 위해 Thread가 wait() 상태가 된다.
  • wait()상태가 된 Thread는 notify()가 호출될 때 까지 기다린다.
  • 유효한 자원이 생기면 notify()가 호출되고 wait()하고 있는 Thread 중 무작위로
     하나의 Thread를 재시작 하도록 한다.
  • notifyAll()이 호출되는 경우 wait()하고 있는 모든 Thread가 재시작 된다.
  • 이 경우 유효한 리소스 만큼의 Thread만이 수행될 수 있고 자원을 갖지 못한 Thread의 경우
    다시 wait()상태로 돌아감.
  • 자바에서는 notifyAll()메서드 사용을 권장

 

 

2. 도서관에서 책을 빌려보자


class Library{
    public ArrayList<String> shelf = new ArrayList<>();

    public Library() {
        shelf.add("book1");
        shelf.add("book2");
        shelf.add("book3");
        shelf.add("book4");
        shelf.add("book5");
    }

    public synchronized String lendBook() throws InterruptedException {
        Thread t = Thread.currentThread();

        while (shelf.size() == 0){
            System.out.println(t.getName() + " : waiting....");
            wait(); //현재 Thread를 wait상태로
            System.out.println(t.getName() + " : waiting....end!");
        }
        if (shelf.size() > 0){
            String book = shelf.remove(0);
            System.out.println(t.getName() + " lend : " + book);
            return book;
        }else {
            return null;
        }

    }

    public synchronized void returnBook(String book){
        Thread t = Thread.currentThread();
        shelf.add(book);
        notifyAll(); //반납했다고 알려주기
        System.out.println(t.getName() + " return : " + book);
    }
}

class Student extends Thread{

    public String name;

    public Student(String name) {
        super(name);
    }

    public void run(){

        try {
            String title = LibraryMain.library.lendBook();
            if(title == null) {
                System.out.println( getName() +" : 책이 없어서 못빌렸음 ㅜㅜ");
                return;
            }
            sleep(5000);
            LibraryMain.library.returnBook(title);
        } catch (InterruptedException e) {
            System.out.println(e);
        }

    }
}

public class LibraryMain {

    public static Library library = new Library();

    public static void main(String[] args) {
        Student std1 = new Student("std1");
        Student std2 = new Student("std2");
        Student std3 = new Student("std3");
        Student std4 = new Student("std4");
        Student std5 = new Student("std5");
        Student std6 = new Student("std6");
        Student std7 = new Student("std7");
        Student std8 = new Student("std8");
        Student std9 = new Student("std9");
        Student std10 = new Student("std10");

        std1.start();
        std2.start();
        std3.start();
        std4.start();
        std5.start();
        std6.start();
        std7.start();
        std8.start();
        std9.start();
        std10.start();

    }
}
std1 lend : book1
std10 lend : book2
std9 lend : book3
std6 lend : book4
std8 lend : book5
==========================
std7 : waiting....
std3 : waiting....
std5 : waiting....
std4 : waiting....
std2 : waiting....
===========================
std8 return : book5
std7 : waiting....end!
std7 lend : book5
std6 return : book4
std9 return : book3
std10 return : book2
std1 return : book1
===========================
std2 : waiting....end!
std2 lend : book4
===========================
std4 : waiting....end!
std4 lend : book3
===========================
std5 : waiting....end!
std5 lend : book2
===========================
std3 : waiting....end!
std3 lend : book1
===========================
std4 return : book3
std2 return : book4
std5 return : book2
std7 return : book5
std3 return : book1

 

  • lendBook()을 호출했는데, shefl.size가 0인 경우 wait상태로 들어가기.
  • shelf.size가 0보다 큰 경우만 책 빌림.
  • lendBook(), returnBook() 을 호출하는 경우 Library객체를 block. ->synchronized
    public synchronized String lendBook() throws InterruptedException {
        Thread t = Thread.currentThread();

        while (shelf.size() == 0){
            System.out.println(t.getName() + " : waiting....");
            wait(); //현재 Thread를 wait상태로
            System.out.println(t.getName() + " : waiting....end!");
        }
        if (shelf.size() > 0){
            String book = shelf.remove(0);
            System.out.println(t.getName() + " lend : " + book);
            return book;
        }else {
            return null;
        }

    }
  • 책을 빌린 후 5초 후에 반납.
    public void run(){

        try {
            String title = LibraryMain.library.lendBook();
            if(title == null) {
                System.out.println( getName() +" : 책이 없어서 못빌렸음 ㅜㅜ");
                return;
            }
            sleep(5000);
            LibraryMain.library.returnBook(title);
        } catch (InterruptedException e) {
            System.out.println(e);
        }

    }

 

 

3. GitHub : 211003 Thread, wait(), notify()


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

'Java > 다양한 기능' 카테고리의 다른 글

멀티 Thread 프로그래밍에서의 동기화  (0) 2021.11.03
Thread 클래스의 메서드  (0) 2021.11.02
Thread  (0) 2021.11.01
Decorator Pattern 예제  (0) 2021.11.01
여러가지 입출력 클래스  (0) 2021.10.31
Comments