-
Notifications
You must be signed in to change notification settings - Fork 0
/
线程同步(对共用对象加锁)
70 lines (67 loc) · 1.57 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
class food {
public int food = 10;
int i;
String s;
public void show() {
System.out.println(s + " runs at "+ i+ " m");
if(food > 0) {
food--;
System.out.println(s + " eats " + i + " th food, remaining " + food + " food");
}
}
}
class MyThread {
public static void main(String[] args) {
MyThread t = new MyThread();
t.go();
}
public void go() {
food f1 = new food();
tortoise t = new tortoise(f1);
rabbit r = new rabbit (f1);
Thread a = new Thread(t);
Thread b = new Thread(r);
a.start();
b.start();
}
}
class tortoise extends Thread {
int i; food fd;
public tortoise(food fd) {
this.fd = fd;
}
public void run() {
for(i = 1;i < 11; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (fd) {
fd.i = i;
fd.s = "tortoise";
fd.show();
}
}
}
}
class rabbit extends Thread {
int i; food fd;
public rabbit (food fd) {
this.fd = fd;
}
public void run() {
for(i = 1;i < 11; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (fd) {
fd.i = i;
fd.s = "rabbit";
fd.show();
}
}
}
}