Java Object类 final void wait(long ms,int ns)方法,带示例
ObjectClassfinalvoidwait(longms,intns)
此方法在java.lang.Object.wait(longms,intns)中可用。
此方法使当前线程等待指定的时间量(以毫秒和纳秒为单位),直到通过调用notify()或notifyAll()对象的方法通知另一个线程为止。
当其他线程中断当前线程时,此方法将引发InterruptedException。
此方法是最终方法,因此无法覆盖。
该方法中给出的时间为毫秒和纳秒。
语法:
final void wait(long ms, int ns){
}参数:
在这里,我们传递了两个时间参数,一个以毫秒为单位,另一个以纳秒为单位(线程必须等待多长时间,即我们必须以毫秒为单位提到时间,如果需要额外的时间,那么我们也可以以纳秒为单位提到时间)Object类的方法中的参数。
返回值:
该方法的返回类型为空,这意味着该方法在执行后不返回任何内容。
Java程序演示对象类的wait(longms,intns)方法的示例
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 Main thread trying to call wait()Thread t2 starts notification Thread t2 trying to given notification Main Thread get notification here 190