1.wait只能在对象锁下使用,不支持类锁,如下的代码运行会报错
synchronized(A.class){
wait();
}
2.wait时当前线程不占有当前对象,其他线程仍然可以使用当前对象;sleep会占用对象锁
public class B {
public synchronized void m1() {
try {
// Thread.sleep(1000);
wait(1000);
System.out.println("m1");
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void m2() {
System.out.println("m2");
}
}
public class A extends Thread {
private B b;
int t;
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public A(B b, int t) {
this.b = b;
this.t = t;
}
@Override
public synchronized void start() {
super.start();
}
@Override
public void run() {
if (this.t == 1) {
b.m1();
} else {
b.m2();
}
}
public static void main(String[] args) {
B b1 = new B();
//B b2 = new B();
Thread ta = new A(b1, 1);
Thread tb = new A(b1, 2);
ta.start();
tb.start();
}
}
如上的代码会先打印m2在打印m1:同一个对象被不同的线程执行时,如果一个线程中有wait不会占用当前对象,另外一个线程正常执行;
如果将wait修改为sleep,会先打印m1再打印m2,因为线程ta会占用对象,直至线程执行完毕。