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开发微信小程序之登录模