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