-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimalRacingExample.java
More file actions
77 lines (64 loc) · 2.06 KB
/
AnimalRacingExample.java
File metadata and controls
77 lines (64 loc) · 2.06 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 example.ThreadExample;
/**
* Compared with thread-based and without thread-based.
*/
public class AnimalRacingExample {
public static void main(String[] args) {
// without thread to run your code.
// ! 執行會是逐步一個一個執行完,才會接續下個任務。
noUseThread();
// use thread to run your code.
// ! 執行會是同時執行,不知道誰才會先執行完任務。
useMultiThread();
}
public static void noUseThread() {
// example without using thread.
AnimalRacingWithoutThread arwt1 = new AnimalRacingWithoutThread("dog");
AnimalRacingWithoutThread arwt2 = new AnimalRacingWithoutThread("cat");
arwt1.run();
arwt2.run();
}
public static void useMultiThread() {
// example with using thread.
AnimalRacingWithThread arwt3 = new AnimalRacingWithThread("hourse");
AnimalRacingWithThread arwt4 = new AnimalRacingWithThread("tiger");
AnimalRacingWithThread arwt5 = new AnimalRacingWithThread("raibbit");
AnimalRacingWithThread arwt6 = new AnimalRacingWithThread("lion");
arwt3.start();
arwt4.start();
arwt5.start();
arwt6.start();
}
}
/**
* 使用單一執行緒 (Without thread)
*
* ! 請注意單一執行緒跟多執行緒差別: 有繼承 Thread class.
*/
class AnimalRacingWithoutThread {
private String name;
AnimalRacingWithoutThread(String name) {
this.name = name;
}
public void run() {
for (int i=0; i<=10; i++) {
System.out.println(name + " is running " + i + " circule.");
}
}
}
/**
* 使用多執行緒 (With thread)
*
* ! 請注意單一執行緒跟多執行緒差別: 有繼承 Thread class.
*/
class AnimalRacingWithThread extends Thread {
private String name;
AnimalRacingWithThread(String name) {
this.name = name;
}
public void run() {
for (int i=0; i<=1000; i++) {
System.out.println(name + " is running " + i + " circule.");
}
}
}