public
void
testAB() {
final
Lock3 lock =
new
Lock3();
Thread a =
new
Thread() {
public
void
run() {
for
(
int
i=
1
;i<
100
;i++) {
lock.lockA();
for
(
int
j=
0
;j<i;j++) {
System.out.print(
"A"
);
}
System.out.println();
lock.unlockA();
}
}
};
Thread b =
new
Thread() {
public
void
run() {
for
(
int
i=
1
;i<
100
;i++) {
lock.lockB();
for
(
int
j=
0
;j<i;j++) {
System.out.print(
"B"
);
}
System.out.println();
lock.unlockB();
}
}
};
a.start();b.start();
try
{ a.join(); b.join(); }
catch
(Exception e) {}
}
public
static
class
Lock3 {
boolean
isAB =
true
;
//true is A, false is B
public
synchronized
void
lockA() {
while
(isAB ==
false
) {
try
{ wait(); }
catch
(Exception e) {}
}
isAB =
true
;
//current is A
}
public
synchronized
void
lockB() {
while
(isAB ==
true
) {
try
{ wait(); }
catch
(Exception e) {}
}
isAB =
false
;
//current is B
}
public
synchronized
void
unlockA() {
isAB =
false
;
//change to B
notify();
}
public
synchronized
void
unlockB() {
isAB =
true
;
//change to A
notify();
}
}