Java Object Class final void wait(long ms)方法,包含示例
JavaObjectClassfinalvoidwait(longms)
在java.lang.Object.wait(longms)中可以使用此方法。
此方法使当前线程等待指定的时间,直到通过调用对象的notify()或notifyAll()方法发出另一个线程通知为止。
当其他线程中断当前线程时,此方法将引发InterruptedException。
此方法是最终方法,因此无法覆盖。
该方法将给出的时间以毫秒为单位。
语法:
final void wait(long ms){
}参数:
我们可以在Object类的方法中将一个对象(线程必须等待多长时间,即必须提到毫秒)作为参数传递。
返回值:
该方法的返回类型为空,这意味着该方法在执行后不返回任何内容。
Java程序演示对象类wait(longms)方法的示例
import java.lang.Object;
public class Thread1 {
public static void main(String[] args) throws InterruptedException {
//创建一个Thread2对象
Thread2 t2 = new Thread2();
//通过调用start(),线程start()将执行
t2.start();
Thread.sleep(1000);
synchronized(t2) {
System.out.println("Main thread trying to call wait()");
//通过调用wait()使当前线程等待
//持续1000毫秒,直到另一个线程通知
t2.wait(1000);
System.out.println("Main Thread get notification here");
System.out.println(t2.total);
}
}
}
class Thread2 extends Thread {
int total = 0;
public void run() {
synchronized(this) {
System.out.println("Thread t2 starts notification");
for (int i = 0; i < 50; ++i) {
total = total + i;
}
System.out.println("Thread t2 trying to given notification");
this.notify();
}
}
}输出结果
D:\Programs>javac Thread1.java D:\Programs>java Thread1 Thread t2 starts notification Thread t2 trying to given notification Main thread trying to call wait()Main Thread get notification here 1225