网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
一、wait() notify() notifyAll()
调用wait()使得线程等待某个条件满足,线程在等待时会被挂起,当其他线程运行时使得这个条件满足时,其他线程会调用notify()或者notifyAll()来唤醒该挂起的线程。
wait()挂起期间,线程会释放锁。假若线程没有释放锁,那么其他线程就无法进入对象的同步方法或同步控制块中,也就无法执行notify() 和 notifyAll()方法来唤醒挂起的线程,从而造成死锁。
使用示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Thread_wait_notify {
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
WaitNotifyExample exam = new WaitNotifyExample();
executorService.execute(() -> exam.after());
executorService.execute(() -> exam.before());
}
}
class WaitNotifyExample{
private Lock lock = new ReentrantLock();
public synchronized void before() {
System.out.println("before func");
notifyAll();
// 唤醒所有线程
}
public synchronized void after(){
try {
wait();
// 执行wait() 操作将线程挂起,该线程会释放锁。 否则其他线程无法进入对象的同步方法或者同步控制块中,
// 就无法执行notify()或notifyAll() 就会造成 死锁
} catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("after func");
}
}
输出:
二、wait() 和 sleep() 的区别
同:
- 都是线程同步时会用到的方法,使当前线程暂停运行,把机会交给其他线程
2.如果任何线程在等待期间被中断都会抛出InterruptedException
3.都是native() 方法
异:
-
wait() 是Object超类中的方法;而sleep()是线程Thread类中的方法
-
对锁的持有不同,wait()会释放锁,而sleep()并不释放锁
-
唤醒方法不完全相同,wait() 依靠notify或者notifyAll 、中断、达到指定时间来唤醒;而sleep()到达指定时间被唤醒.
-
使用位置不同,wait只能在同步代码块或同步控制块中使用,而sleep可以在任何位置使用。
三、await() signal() 和 signalAll()
java.util.concurrent类库中提供的Condition类来实现线程之间的协调。
在Condition上调用 await() 方法使线程等待,其他线程调用signal() 或 signalAll() 方法唤醒等待的线程。
ReentrantLock里面默认有实现newCondition()方法,新建一个条件对象。
下面使用Lock来获取一个Condition对象,使用重入锁ReentrantLock。
代码示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Thread_await_signal {
public static void main(String[] args){
ExecutorService executorService = Executors.newCachedThreadPool();
AwaitSignalExample exam = new AwaitSignalExample();
executorService.execute(() -> exam.after());
executorService.execute(() -> exam.before());
}
}
![img](https://img-blog.csdnimg.cn/img_convert/e6e98e989ece8678b2ddd89dbb83759e.png)
![img](https://img-blog.csdnimg.cn/img_convert/ea5482a095b05aefd1cb8ac0fb94e212.png)
![img](https://img-blog.csdnimg.cn/img_convert/0189ed210eeb39d355143ce9bc824851.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Go语言开发知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**
**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[如果你需要这些资料,可以戳这里获取](https://bbs.csdn.net/topics/618658159)**