forked from coding-technology/JavaCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTicketsDemo.java
More file actions
41 lines (33 loc) · 995 Bytes
/
TicketsDemo.java
File metadata and controls
41 lines (33 loc) · 995 Bytes
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
import java.nio.channels.SeekableByteChannel;
public class TicketsDemo implements Runnable {
private int tickets = 10000 ;
//买火车票
@Override
public void run() {
while(true){
//买火车票
sell();
}
}
// public synchronized void sell(){
// if(tickets > 0){
// tickets -- ;
// System.out.println(Thread.currentThread().getName()+"-正在售卖,剩余票数:" + tickets );
// }
// }
public void sell(){
synchronized (this) {
if (tickets > 0) {
tickets--;
System.out.println(Thread.currentThread().getName() + "-正在售卖,剩余票数:" + tickets);
}
}
}
public static void main(String[] args) {
TicketsDemo ticket = new TicketsDemo() ;//Rnnable
Thread a = new Thread(ticket,"a");
Thread b = new Thread(ticket,"b");
a.start();
b.start();
}
}