-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSellTickets.java
More file actions
executable file
·43 lines (37 loc) · 1.01 KB
/
SellTickets.java
File metadata and controls
executable file
·43 lines (37 loc) · 1.01 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
package basic.thread;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* ��Ʊ����
*
* @author yangqc
*/
public class SellTickets implements Runnable {
private static volatile int TICKET_NUM = 1000;
private static final Lock lock = new ReentrantLock();
private static final Condition condition = lock.newCondition();
@Override
public void run() {
lock.lock();
try {
while (TICKET_NUM > 0) {
System.out.println(Thread.currentThread().getName() + " * " + --TICKET_NUM);
condition.signalAll();
condition.await();
}
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
SellTickets task = new SellTickets();
for (int i = 0; i < 10; i++) {
new Thread(task).start();
}
}
}