상세 컨텐츠

본문 제목

[쓰레드 동기화] 책빌리기

자바

by esoesmio 2023. 4. 4. 09:52

본문

package april3;

public class class7 {

    public static void main(String[] args) {

        System.out.println("현재 대출한 책의 갯수 " + library.student.getBookcount());

        borrowthread b = new borrowthread();
        returnthread r = new returnthread();

        b.setPriority(10);
        b.start();
        r.start();
        try {
            b.join();
            r.join();
        } catch (InterruptedException e) {


        }

    }
}

class student{
    public int getBookcount() {
        return bookcount;
    }

    public void setBookcount(int bookcount) {
        this.bookcount = bookcount;
    }

    int bookcount = 5;


    public synchronized void borrowbook() throws InterruptedException{
        int m = bookcount;
        Thread.sleep(1000);
        bookcount = m+1;
        System.out.println("대출완료");

    }

    public  synchronized  void returnbook() throws InterruptedException{
        int m = bookcount;
        Thread.sleep(1000);
        bookcount = m-1;
        System.out.println("반납완료");

    }

}
class library{
    public static student student = new student();


}

class borrowthread extends  Thread{
    @Override
    public   void run(){
        try {
            library.student.borrowbook();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(
                "학생이 빌린 총 책의 갯수 : " + library.student.getBookcount());


    }



}

class returnthread extends Thread{


    public    void   run(){
        try {
            library.student.returnbook();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(
                "학생이 빌린 총 책의 갯수 : " + library.student.getBookcount());


    }


}

'자바' 카테고리의 다른 글

[람다 함수] 돈바꾸기  (0) 2023.04.04
[람다인터페이스] 소문자 대문자로 바꾸는거  (0) 2023.04.04
[쓰레드종료] interrupt로  (0) 2023.04.03
[쓰레드 종료] while로  (0) 2023.04.03
[스레드 동기화] notify wait  (0) 2023.04.03

관련글 더보기

댓글 영역