forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTakeMoneyFromAccountExampleTest.java
More file actions
51 lines (42 loc) · 1.04 KB
/
TakeMoneyFromAccountExampleTest.java
File metadata and controls
51 lines (42 loc) · 1.04 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
package com.examplehub.basics.thread;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class TakeMoneyFromAccountExampleTest {
@Test
void test() throws InterruptedException {
class Account implements Runnable {
private int balance;
public Account() {}
public Account(int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
@Override
public void run() {
synchronized (this) {
if (balance >= 100) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance -= 100;
}
}
}
}
Account account = new Account(1000);
Thread t1 = new Thread(account);
Thread t2 = new Thread(account);
Thread t3 = new Thread(account);
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
assertEquals(700, account.getBalance());
}
}