프로그래밍/Java
[자바/java] synchronized 데이터 중복사용 방지, 좌석예약
Rolen
2023. 2. 5. 22:24
package q8;
class Seat {
static int usable = 10;
synchronized void print(String name, int n) {
System.out.println(name + " 접속\n가능한 좌석수: " + usable + " / 요청 좌석 수: " + n);
if (usable >= n && usable > 0) {
System.out.println("좌석 수: " + n + ", 예약완료");
usable -= n;
} else {
System.out.println("좌석 예약이 불가합니다.");
}
System.out.println(name + " 접속해제\n");
}
}
class People1 extends Thread {
Seat seat;
int num = 5;
People1(Seat s) {
seat = s;
}
public void run() {
seat.print(getName(), num); // 요청하는 좌석의 수 : 5
}
}
class People2 extends Thread {
Seat seat;
int num = 4;
People2(Seat s) {
seat = s;
}
public void run() {
seat.print(getName(), num); // 요청하는 좌석의 수 : 4
}
}
class People3 extends Thread {
Seat seat;
int num = 2;
People3(Seat s) {
seat = s;
}
public void run() {
seat.print(getName(), num); // 요청하는 좌석의 수 : 2
}
}
public class Q8 {
public static void main(String[] args) {
Seat obj = new Seat();
People1 p1 = new People1(obj);
People2 p2 = new People2(obj);
People3 p3 = new People3(obj);
p1.start();
p2.start();
p3.start();
}
}
728x90