java wait的用法

public class Test3 {
public static void main(String[] args) {
tt1 t1 = new tt1("第一");
tt1 t2 = new tt1("第二");

t1.start();
t2.start();
synchronized (t1) {
try {
t1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

while(true){
System.out.println("B");
}
}
}
class tt1 extends Thread{
private String name;
private int i =0;
public tt1(String name){
this.name = name;
}
@Override
public void run() {
while(true){
i++;
if(i==110) notify();
System.out.println(this.name+i);
}
}
@Override
public String toString() {
return this.name;
}
}

求大神帮忙看看,按照道理,wait就是把当前的线程阻塞,然后等我i加到110的时候,然后再把主线程激活,这样最后应该是三个线程交互执行,但是开始还是交互输出第一x,第二x,但是不久马上结果只输出
B,这是我是你,最后不是应该三个线程交互输出么?第一x,第二x, B相互输出,其解释
还有为什么要在synchronized (t1) {}内来执行wait?为什么呢

wait是Object的方法,也就是说可以对任意一个对象调用wait方法,调用wait方法将会将调用者的线程挂起,直到其他线程调用同一个对象的notify方法才会重新激活调用者,例如:

//Thread 1

try{
obj.wait();//suspend thread until obj.notify() is called
}
catch(InterrputedException e) {
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-07-11
>>您给出的代码我本地报错:
Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.IllegalMonitorStateException: current thread not owner
at java.lang.Object.notify(Native Method)
at tt1.run(Test.java:555)

原因:锁对象是t1,但进入的t2对象,即两个线程不一致.本回答被提问者采纳