8

Java wait,join,notify解析

 3 years ago
source link: https://1fishman.github.io/2019/06/22/Java-wait-join-notify%E8%A7%A3%E6%9E%90/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java wait,join,notify解析

2019-06-22

|

2019-07-01

| Views: 20

wait()

wait()方法只能在对象上调用,比如 obj.wait(),表明将当前线程阻塞,直到有其他线程调用此对象的notify()或notifyAll()方法.线程才会继续执行. 或者有其他线程中断了此线程,将会抛出一个中断异常.

wait(long timeout)

和wait()方法类似,但是此等待是有超时限制的,当等待的时间到了,也会自动被唤醒

wait(long timeout,int nanos)

此方法就有点意思了,看名字好像等待超时时间的控制精确到了纳秒级别,但是看看源码就了解到了,事实并不是如此.

public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}

可以看到,如果nanos大于0,则直接将timeout++,也就是说如果有设置纳秒参数,则再加1毫秒.所以,等待超时只能精确到毫秒级别

notify

notify就很简单了,就是随机唤醒一个在此对象上等待的线程.

notifyAll()

All就是所有,就是唤醒在此对象上等待的线程

yield

他是thread的静态方法,对当前线程有效
yield()方法,此方法就是让出cpu的执行权,意思就是我不干了,你们谁有事谁就干吧.让出执行权,让其他线程去干活.
但是这个让出指的是让所有的线程重新争夺cpu的执行权,包括自己,所以,还是有可能继续轮到自己干的.

join()

join方法是在Thread类中的方法,调用join方法就是等待此线程执行完成,之后再执行.比如下面代码:

public static void main(String[] args) throws InterruptedException {
int a = 10;
Thread thread1= new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// 省略代码
}
});
thread1.start();
thread1.join();
}

在这里调用thread1.join()方法,就会将当前线程阻塞,知道thread1()完成返回之后才会继续执行


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK