Java Object类 final void void wait()方法,带有示例
对象类finalvoidwait()
此方法在java.lang.Object.wait()中可用。
此方法通过调用对象的notify()或notifyAll()方法使当前线程等待直到另一个线程通知。
当其他线程中断当前线程时,此方法将引发InterruptedException。
此方法是最终方法,因此无法覆盖。
语法:
final void wait(){
}参数:
我们不会在Object类的方法中将任何对象作为参数传递。
返回值:
该方法的返回类型为空,这意味着该方法在执行后不返回任何内容。
Java程序演示对象类wait()方法的示例
import java.lang.Object;
public class Thread1 {
public static void main(String[] args) throws InterruptedException {
//创建一个Thread2对象
Thread2 t2 = new Thread2();
//通过调用start(),线程start()将执行
t2.start();
synchronized(t2) {
System.out.println("Main thread trying to call wait()");
//通过调用wait()导致当前线程
//等到另一个线程执行
t2.wait();
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 < 100; ++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 4950
热门推荐
10 春节拜年祝福语儿童简短
11 老师简短祝福语有哪些
12 毕业离别祝福语简短老师
13 送菜的祝福语简短霸气
14 桔梗配什么祝福语简短
15 祝福语简短唯美10字
16 道教生日祝福语简短大全
17 恋爱祝福语大全简短搞笑
18 婚礼美句简短祝福语