forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT19.java
More file actions
133 lines (113 loc) · 3.16 KB
/
T19.java
File metadata and controls
133 lines (113 loc) · 3.16 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package com.basic; /**
* @program JavaBooks
* @description: 售票程序
* @author: mf
* @create: 2019/12/31 18:36
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.TimeUnit;
/**
* 有N张火车票,每张票都有一个编号
* 同时有10个窗口对外售票
*
*/
public class T19 {
private static List<String> tickets = new ArrayList<>();
static {
for (int i = 0; i < 1000; i++) {
tickets.add("票编号:" + i);
}
}
public static void main(String[] args) {
// 10个窗口售票
for (int i = 0; i < 10; i++) {
new Thread(() -> {
while (tickets.size() > 0) {
// size和remove不是原子性的
System.out.println("销售了--" + tickets.remove(0));
}
}).start();
}
}
}
/**
* 用vector安全容器
*/
class T19_1 {
private static Vector<String> lists = new Vector<>();
static {
for (int i = 0; i < 1000; i++) {
lists.add("编号:" + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
while (lists.size() > 0) {
// 加点延迟
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 但是size和remove之间不是原子性的
System.out.println("销售了--" + lists.remove(0));
}
}).start();
}
}
}
/**
* 用synchroized
*/
class T19_2 {
private static List<String> lists = new ArrayList<>();
static {
for (int i = 0; i < 1000; i++) {
lists.add("编号:" + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
while (true) {
synchronized (lists) {
if (lists.size() <= 0) break;
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("销售了--" + lists.remove(0));
}
}
}).start();
}
}
}
/**
* 使用并发容器队列
*/
class T19_3 {
private static Queue<String> lists = new ConcurrentLinkedDeque<>();
static {
for (int i = 0; i < 1000; i++) {
lists.add("编号:" + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() -> {
while (true) {
String s = lists.poll();
if (s == null) break;
else System.out.println("销售了--" + s);
}
}).start();
}
}
}