-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathThreadDemo.java
69 lines (64 loc) · 1.93 KB
/
ThreadDemo.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
/**
* Демонстрация работы с потоками
*/
public class ThreadDemo {
private static final int ITERATIONS = 1000;
static Integer counter = 0;
static MyClass myClass = new MyClass();
public static void main(String[] args) {
int sleep = 1;
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < ITERATIONS; i++) {
myClass.inc();
counter++;
System.out.println("1) i = " + i);
if (sleep > 0)
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread1.start();
// Лямбда-выражения
Thread thread2 = new Thread(() -> {
for (int i = 0; i < ITERATIONS; i++) {
myClass.inc();
counter++;
System.out.println("2) i = " + i);
if (sleep > 0)
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("counter = " + counter);
System.out.println("myClass.counter = " + myClass.counter);
}
static class MyClass {
int counter = 0;
void inc() {
//counter++;
synchronized (this) {
counter++;
}
}
// this
public synchronized void inc2() {
counter++;
}
}
}