1、wait、notify方法
1.1、wait、notify必须在synchronized中进行使用
public class Res {
public String userSex;
public String userName;
public boolean flag = false;
}
public class InThread extends Thread {
private Res res;
public InThread(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.userSex = "男";
} else {
res.userName = "小红";
res.userSex = "女";
}
count = (count + 1) % 2;
res.flag = true;
res.notify();
}
}
}
}
public class OutThread extends Thread {
private Res res;
public OutThread (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.userSex);
res.flag = false;
res.notify();
}
}
}
}
public class ThreadApp {
public static void main(String[] args) {
Res res = new Res();
InThread in = new InThread(res);
OutThread out = new OutThread(res);
in.start();
out.start();
}
}
2、wait、sleep的区别
2.1、sleep属于Thread的方法,wait属于Object的方法
2.2、sleep方法导致程序暂停执行时间,让出cpu给其他线程,但是他的监控状态依然保持着,当指定时间到了又会自动恢复运行状态。
2.3、在调用sleep方法时,线程不会释放对象锁。而当调用wait方法时,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对次对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。
3、lock锁
lock锁与synchronized关键字类似的同步功能,但需要在使用时手动获取锁和释放锁。
Lock lock = new ReentrantLook();
lock.lock();
try{
// 可能会出现线程安全的操作
} finally {
// 一定在finally中释放锁
lock.unlock();
}