Wait、Notify()用法
- 两个方法都属于Object类中的,使用过程中涉及到对象锁,必须放在synchronized中使用
- wait会暂停当前的线程,线程变为阻塞状态,释放cpu执行资格,同时释放锁
- Notify唤醒锁池正在等待的线程
代码例子
package com.mayikt;
/**
* @Description:
* @Author: ChenYi
* @Date: 2020/07/19 09:18
**/
public class Thread007 {
class Res {
private String username;
private String sex;
private boolean flag;
}
class InputThread extends Thread {
private Res res;
public InputThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (res) {
if (res.flag) {
try {
res.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count == 0) {
res.username = "菜头";
res.sex = "男";
} else {
res.username = "小俊";
res.sex = "女";
}
res.flag = true;
res.notify();
count = (++count) % 2;
}
}
}
}
class OutputThread extends Thread {
private Res res;
public OutputThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if (!res.flag) {
try {
res.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(res.username + " " + res.sex);
res.flag = false;
res.notify();
}
}
}
}
public static void main(String[] args) {
Thread007 thread007 = new Thread007();
thread007.init();
}
private void init() {
Res res = new Res();
InputThread inputThread = new InputThread(res);
OutputThread outputThread = new OutputThread(res);
inputThread.start();
outputThread.start();
}
}
wait和sleep的区别
wait是属于object类中的方法,sleep是属于Thread类的,两个都是线程变为阻塞状态,但wait是释放锁的,sleep是没有释放锁的
多线程的join
使用join保证线程的顺序问题,比如A和B两个线程,如果B线程调用A.join方法,B.线程会阻塞同时释放锁,则必须让A线程执行完毕,才能执行B线程,底层通过wait和notify实现
package com.mayikt;
/**
* @Description:
* @Author: ChenYi
* @Date: 2020/07/19 10:30
**/
public class Thread010 implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ",主线程执行");
}
public static void main(String[] args) {
try {
Thread a1 = new Thread(new Thread010(), "A1线程");
Thread a2 = new Thread(new Thread010(), "A2线程");
Thread a3 = new Thread(new Thread010(), "A3线程");
a1.start();
a1.join();
a2.start();
a2.join();
a3.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
参考:蚂蚁课堂