-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path线程同步(对共用方法加锁)
57 lines (54 loc) · 1.27 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
class food {
public int food = 10;
int i;
String s;
public synchronized void show (int i1, String s1) {
i = i1; s = s1;
System.out.println(s + " runs at "+ i + " m");
if(food > 0) {
food--;
System.out.println(s + " eats " + i + " th food, remaining " + food + " food");
}
}
}
public 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);
t.start();
r.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) {}
fd.show(i,"tortoise");
}
}
}
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) {}
fd.show(i,"rabbit");
}
}
}