forked from liujiboy/Java_Course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest7.java
More file actions
59 lines (51 loc) · 1.14 KB
/
Test7.java
File metadata and controls
59 lines (51 loc) · 1.14 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
package cqu;
public class Test7 {
public static int n = 10;
public static Object lock = new Object();
public static void main(String args[]) throws InterruptedException {
long start=System.nanoTime();
Customer customers[] = new Customer[300000];
for (int i = 0; i < customers.length; i++) {
customers[i] = new Customer(i);
customers[i].start();
}
int count = 0;
for (int i = 0; i < customers.length; i++) {
customers[i].join();
if (customers[i].isFlag()) {
System.out.println(customers[i].getCustomerId());
count++;
}
}
System.out.println("实际个数:" + count);
long end=System.nanoTime();
System.out.println(end-start);
}
}
class Customer extends Thread {
private int customerId;
private boolean flag = false;
public void run() {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Test7.lock) {
if (Test7.n != 0) {
flag = true;
Test7.n--;
}
}
}
public int getCustomerId() {
return customerId;
}
public boolean isFlag() {
return flag;
}
public Customer(int customerId) {
super();
this.customerId = customerId;
}
}