线程A:2
线程A:3
线程B:4
线程B:5
线程B:6
线程A:7
线程A:8
线程A:9
p
ublic
class
Test{
public
static
Object obj =
new
Object();
public
static
void
main(String[] args){
new
A().start();
new
B().start();
}
}
class
A
extends
Thread{
public
void
run(){
try
{
synchronized
(Test.obj){
for
(
int
i =
1
; i <
31
;i +=
6
){
Test.obj.notify();
System.out.println(
"线程A:"
+ i);
System.out.println(
"线程A:"
+ (i+
1
));
System.out.println(
"线程A:"
+ (i+
2
));
Test.obj.wait();
}
}
}
catch
(Exception e){
e.printStackTrace();
}
}
}
class
B
extends
Thread{
public
void
run(){
try
{
synchronized
(Test.obj){
for
(
int
i =
4
; i <
31
;i +=
6
){
Test.obj.notify();
System.out.println(
"线程B:"
+ i);
System.out.println(
"线程B:"
+ (i+
1
));
System.out.println(
"线程B:"
+ (i+
2
));
Test.obj.wait();
}
}
}
catch
(Exception e){
e.printStackTrace();
}
}
}
sleep是线程类(Thread)的方法,导致此线程暂停执行指定时间,给执行机会给其他线程,但是监控状态依然保持,到时后会自动恢复。调用sleep不会释放对象锁。
wait是Object类的方法,对此对象调用wait方法导致本线程放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象发出notify方法(或notifyAll)后本线程才进入对象锁定池准备获得对象锁进入运行状态。