-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadDemo2.java
70 lines (61 loc) · 1.92 KB
/
ThreadDemo2.java
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
/**
* Демонстрация работы с потоками
*/
public class ThreadDemo2 {
static MyClass myClass = new MyClass();
public static void main(String[] args) {
final Object lock = new Object();
// Первый поток
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 98; i++) {
synchronized (lock) {
myClass.inc(1000);
System.out.println("1) i = " + myClass.getCounter());
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
// Второй поток
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 99; i++) {
synchronized (lock) {
myClass.inc(1);
System.out.println("2) i = " + myClass.getCounter());
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread2.start();
thread1.start();
try {
thread2.join();
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("myClass.counter = " + myClass.getCounter());
}
static class MyClass {
int counter = 0;
public synchronized void inc(int value) {
counter += value;
}
public synchronized int getCounter() {
return counter;
}
}
}