Java并发:join与wait
程序员文章站
2023-12-24 19:17:39
Thread.join中使用Object.wait实现: //java.lang.Thread public final synchronized void join(long millis) throws InterruptedException { long base = System.curr ......
thread.join中使用object.wait实现:
//java.lang.thread
public final synchronized void join(long millis)
throws interruptedexception {
long base = system.currenttimemillis();
long now = 0;
if (millis < 0) {
throw new illegalargumentexception("timeout value is negative");
}
if (millis == 0) {
while (isalive()) {
wait(0);
}
} else {
while (isalive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = system.currenttimemillis() - base;
}
}
}
wait方法,jdk文档中的解释时:causes the current thread to wait ,wait方法会让当前线程从runnable变成waitting的状态。怎么理解这句话呢?首先每个对象都可以作为一个锁,wait方法是根类object的方法,每个对象都有其wait方法,在main方法中执行如下代码:
public class program{
public static void main(string[] args) throws exception{
mythread mythread = new thread(new runnable(){
@override
public void run() {
//this就是当前对象mythread,同步获取到mythread锁
synchronized (this) {
this.notify();//唤醒在mythread锁上等待的单个线程。即main主线程从waitting变成runnable,main方法继续执行
}
}
});
mythread.setname("mythread");
mythread.start();
//同步获取到mythread锁
synchronized (mythread) {
//使当前线程(main)从runnable进入waitting状态,等待其他某个线程调用mythread锁的 notify方法
mythread.wait();
}
}
mythread对象就是一个锁,main方法synchronized (mythread)获取到锁,并执行该锁的wait方法,使main线程一直等待,当线程mythread中获取同一个锁,并执行该锁的notify方法,使之前因该锁等待main方法可以继续执行。