wait()函数怎么用?

applebibo 2002-12-25 03:54:57
JB中很多类都有wait();wait(long);wait(long,int);的方法,不知道是干什么用的,怎么用呢?我定义了一个类的实例a,然后执行a.wait(1000);然后出错:
java.lang.IllegalMonitorStateException: current thread not owner
我觉得就是wait用的不对,那我想让程序停顿一段时间是不是就不能用wait智能用时间的类了?wait()到底怎么用,如果里面的long代表时间,那单位是什么,wait(1000)代表等待1000什么?
...全文
267 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wenandwu 2002-12-26
  • 打赏
  • 举报
回复
wait()和notify()可以实现线程对资源访问的同步.但他们必须在synchronized子句中执行,就是说他们的执行条件是必须取得相应的对象机锁.wait()会释放自己所占有的机锁,因此他比sleep(),suspend()等等有效率得多,不过多数用在两个现成之间的同步.
披星戴月 2002-12-25
  • 打赏
  • 举报
回复
wait()让线程进入等待状态,
相对应的有notify(叫醒一个类)与notifyAll(叫醒所有类)
希偌 2002-12-25
  • 打赏
  • 举报
回复
import java.lang.Runnable;
import java.lang.Thread;

public class bean8 implements Runnable{

public bean8() {
TestThread testthread1 = new TestThread(this,"1");
TestThread testthread2 = new TestThread(this,"2");

testthread2.start();
testthread1.start();


}

public static void main(String[] args) throws Exception {
new bean8();
}


public void run(){

TestThread t = (TestThread) Thread.currentThread();
try{
if (!t.getName().equalsIgnoreCase("1")) {
synchronized(this) {
wait();
}
}
while(true){

System.out.println("@time in thread"+ t.getName()+ "="+ t.increaseTime());

if(t.getTime()%10 == 0) {
synchronized(this) {
System.out.println("****************************************");
notify();
if ( t.getTime()==100 ) break;
wait();
}
}
}
}catch(Exception e){e.printStackTrace();}
}

}

class TestThread extends Thread{
private int time = 0 ;
public TestThread(Runnable r,String name){
super(r,name);
}
public int getTime(){
return time;
}
public int increaseTime (){
return ++time;
}


}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧