-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHomeWork.java
More file actions
76 lines (57 loc) · 1.86 KB
/
HomeWork.java
File metadata and controls
76 lines (57 loc) · 1.86 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
package com.example.demo;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 还没搞懂,这是抄来的,对不起,我跟不上了。
*/
public class HomeWork {
public static void main(String[] args) {
long start=System.currentTimeMillis();
// 在这里创建一个线程或线程池,
// 异步执行 下面方法
System.out.printf("当前主线程[%s]\n", Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
runWithWait();
}
int result = sum(); //这是得到的返回值
// 确保 拿到result 并输出
System.out.println("异步计算结果为:"+result);
System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms");
// 然后退出main线程
}
private static int sum() {
return fibo(36);
}
private static int fibo(int a) {
if ( a < 2)
return 1;
return fibo(a-1) + fibo(a-2);
}
/**
* 使用wait的方式来实现
*/
private static void runWithWait() {
long start=System.currentTimeMillis();
final AtomicInteger num = new AtomicInteger(0);
Thread thread = new Thread() {
@Override
public void run() {
synchronized (num) {
num.set(sum());
num.notifyAll();
}
}
};
thread.start();
synchronized (num) {
if (num.get() == 0) {
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// System.out.println("异步计算结果为:"+num.get());
// System.out.println("使用时间:"+ (System.currentTimeMillis()-start) + " ms");
}
}