wait/notify/notifyAll在Object类中
wait/notify/notifyAll在Object类中
因为我们在使用synchronized锁 对象锁可以是任意对象,所以wait/notify/notifyAll需要放在Object类中。
wait/notify/简单的用法
public class Thread03 extends Thread {
@Override
public void run() {
try {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + “>>当前线程阻塞,同时释放锁!<<”);
this.wait();
}
System.out.println(">>run()<<");
} catch (InterruptedException e) {
}
多线程通讯实现生产者与消费者
public class Thread04 {
class Res {
/**
* 姓名
/
private String userName;
/*
* 性别
/
private char sex;
/*
* 标记
*/
private boolean flag = false;
}
}
/**
- flag 默认值==false
- flag false 输入线程 输入值 输出线程 先拿到锁 释放锁
- flag true 输出线程 输出值
*/
public boolean flag = false;
Join/Wait与sleep之间的区别
sleep(long)方法在睡眠时不释放对象锁
join(long)方法先执行另外的一个线程,在等待的过程中释放对象锁 底层是基于wait封装的,
Wait(long)方法在等待的过程中释放对象锁
三个线程 T1,T2,T3,怎么确保它们按顺序执行?
Thread t1 = new Thread(() -> System.out.println(Thread.currentThread().getName() + “,线程执行”), “t1”);
Thread t2 = new Thread(() -> System.out.println(Thread.currentThread().getName() + “,线程执行”), “t2”);
Thread t3 = new Thread(() -> System.out.println(Thread.currentThread().getName() + “,线程执行”), “t3”);
t1.start();
t2.start();
t3.start();
public class Thread05 {
public static void main(String[] args) throws InterruptedException {Thread t1 = new Thread(() -> {try {Thread.sleep(3000);} catch (Exception e) {}System.out.println(Thread.currentThread().getName() + ",线程执行");}, "t1");Thread t2 = new Thread(() -> {try {t1.join();} catch (InterruptedException e) {}System.out.println(Thread.currentThread().getName() + ",线程执行");}, "t2");Thread t3 = new Thread(() -> {try {t2.join();} catch (InterruptedException e) {}System.out.println(Thread.currentThread().getName() + ",线程执行");}, "t3");t1.start();t2.start();t3.start(); }}
总结
以上是生活随笔为你收集整理的wait/notify/notifyAll在Object类中的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 等待/通知机制
- 下一篇: 使用uni-app开发微信小程序之登录模