PS : 인터뷰에서이 질문을 만났기 때문에 링크가 없습니다.이 질문이 매우 흥미 롭다고 생각되면 저와 공유해주세요.
제목 설명
100 매의 매표소가 있고 매표소가 세 개 있고 세 매표소가 독립되어 각각 자체 판매하고 있지만 매표소는 독립되어 있지 않으며 각 매표소는 반복적으로 판매 할 수 없습니다.
참고 :
100 장의 티켓을 모두 판매해야하지만 더 이상 판매 할 수 없습니다.
각 창은 100 밀리 초마다 티켓을 판매합니다.
요구 사항 :
각 티켓을 판매 한 창구 출력
아이디어
티켓이 부적절하게 작동되면 반복적으로 판매되기 때문에 이것은 일반적인 다중 스레드 안전 문제입니다.
따라서이 질문의 요점은 당시 남은 티켓 수를 확인하고 티켓을 얻는 두 가지 작업이 각 매표소에서 동기화되어야한다는 것입니다.
그런 다음 동기화 방법을 사용하여 위의 두 작업의 동기화를 보장합니다.
class Store {
private volatile int ticket = 1;
/**
* A售票口
* @throws InterruptedException
*/
public void A() throws InterruptedException {
int temp;
while ((temp = getSetTicket()) != -1) {
System.out.println(temp + " A");
Thread.sleep(100);
}
}
/**
* B售票口
* @throws InterruptedException
*/
public void B() throws InterruptedException {
int temp;
while ((temp = getSetTicket()) != -1) {
System.out.println(temp + " B");
Thread.sleep(100);
}
}
/**
* 售票口
* @throws InterruptedException
*/
public void C() throws InterruptedException {
int temp;
while ((temp = getSetTicket()) != -1) {
System.out.println(temp + " C");
Thread.sleep(100);
}
}
/**
* 查看票和取票的同步操作
* @return
*/
public synchronized int getSetTicket() {
int temp = this.ticket;
//查看此时票是否能卖出
if (temp > 100) {
return -1;
}
//取票
this.ticket++;
return temp;
}
}
테스트
세 개의 스레드가 동시에 세 개의 창을 호출하도록 설정
public static void main(String[] args) throws InterruptedException {
Store store = new Store();
new Thread(new Runnable() {
@Override
public void run() {
try {
store.A();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
store.B();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
store.C();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(1000);
}
시험 결과
1 A
2 B
3 C
4 A
6 C
5 B
7 A
8 C
9 B
10 A
11 C
12 B
13 A
14 C
15 B
16 A
17 C
18 B
19 A
20 C
21 B
22 A
23 C
24 B
25 A
26 C
27 B
28 A
29 C
30 B
31 A
33 B
32 C
34 A
35 C
36 B
37 A
38 C
39 B
40 A
41 B
42 C
43 A
45 C
44 B
46 A
48 B
47 C
49 A
50 C
51 B
52 A
53 C
54 B
55 A
56 B
57 C
58 A
59 B
60 C
61 A
62 B
63 C
64 A
66 B
65 C
67 A
68 B
69 C
70 A
72 C
71 B
73 A
74 C
75 B
76 A
77 C
78 B
79 A
80 C
81 B
82 A
83 C
84 B
85 A
87 B
86 C
88 A
89 B
90 C
91 A
92 B
93 C
94 A
95 B
96 C
97 A
98 B
99 C
100 A
Process finished with exit code 0