forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExampleThreadTest.java
More file actions
103 lines (88 loc) · 2.36 KB
/
ExampleThreadTest.java
File metadata and controls
103 lines (88 loc) · 2.36 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
package com.examplehub.basics.thread;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class ExampleThreadTest {
@Test
void test() throws Exception {
class ExampleThread extends Thread {
private int sum = 0;
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = 1; i <= 100; ++i) {
sum += i;
}
}
}
ExampleThread thread = new ExampleThread();
thread.start();
thread.join(); // main thread wait unit sub thread completed
assertEquals(5050, thread.getSum());
}
@Test
void testAnonymous() {
new Thread(() -> System.out.println("testAnonymous")).start();
}
@Test
@Disabled // TODO build fail on gradle platform
void testGetThreadId() {
new Thread(() -> assertTrue(Thread.currentThread().getId() > 1)).start();
assertEquals(1, Thread.currentThread().getId());
}
@Test
@Disabled // TODO build fail on gradle platform
void testGetThreadName() {
class ExampleThread extends Thread {
public ExampleThread(String name) {
super(name);
}
@Override
public void run() {
assertEquals("sub-thread", getName());
}
}
new ExampleThread("sub-thread").start();
new Thread(
() -> assertEquals("second-sub-thread", Thread.currentThread().getName()),
"second-sub-thread")
.start();
assertEquals("main", Thread.currentThread().getName());
}
@Test
void testSumOddEven() throws InterruptedException {
class OddSumThread extends Thread {
private int sum = 0;
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = 1; i <= 99; i += 2) {
sum += i;
}
}
}
class EvenSumThread extends Thread {
private int sum = 0;
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
}
}
OddSumThread oddSumThread = new OddSumThread();
EvenSumThread evenSumThread = new EvenSumThread();
oddSumThread.start();
evenSumThread.start();
oddSumThread.join();
evenSumThread.join();
assertEquals(5050, oddSumThread.getSum() + evenSumThread.getSum());
}
}