-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadLock.java
More file actions
46 lines (44 loc) · 1.5 KB
/
Copy pathThreadLock.java
File metadata and controls
46 lines (44 loc) · 1.5 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
package MultiThreadTest;
public class ThreadLock {
private static int a = 1;
private static Object lock = new Object ();
public static void main (String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread () {
public void run () {
while (a <= 10)
synchronized (lock) {
if (a % 2 == 1) {
System.out.println ("t1:" + a++);
} else {
lock.notifyAll ();
try {
lock.wait (1000);
} catch (InterruptedException e) {
e.printStackTrace ();
}
}
}
}
};
Thread t2 = new Thread () {
public void run () {
while (a <= 10)
synchronized (lock) {
if (a % 2 == 0) {
System.out.println ("t2:" + a++);
} else {
lock.notifyAll ();
try {
lock.wait (1000);
} catch (InterruptedException e) {
e.printStackTrace ();
}
}
}
}
};
t1.start ();
t2.start ();
}
}