> wait () 立刻停止该线程,释放锁,让其他等等获取该锁的线程执行
> notify() 发出通知停止该线程, 但 notify() 不会立刻停止该线程 当前代码块执全部行结束后,释放锁,让等待的线程获取锁,再执行
> 案例
import java.util.ArrayList;
import java.util.List;
class Service {
private final Object lock = new Object();
private final List<Integer> list = new ArrayList();
public void methodWait() {
try {
synchronized (lock) {
if (list.size() != 5) {
System.out.println("start methodWait -- " + System.currentTimeMillis() + "--" + Thread.currentThread().getName());
System.out.println(" 立刻停止该线程,释放锁,让其他等等获取该锁的线程执行");
lock.wait();
System.out.println("end methodWait -- " + System.currentTimeMillis() + "--" + Thread.currentThread().getName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void methodNotify() {
try {
synchronized (lock) {
System.out.println("start methodNotify -- " + System.currentTimeMillis() + Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
System.out.println("add次数:" + i);
list.add(i);
if (list.size() == 5) {
lock.notify();
System.out.println("发出通知停止该线程, 但 notify() 不会立刻停止该线程 当前代码块执全部行结束后,释放锁,让等待的线程获取锁,再执行" + Thread.currentThread().getName());
}
Thread.sleep(100);
}
System.out.println(" end methodNotify 这里执行后就释放锁-- " + System.currentTimeMillis() + "--" + Thread.currentThread().getName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ThreadOne extends Thread {
private Service service;
public ThreadOne(Service service) {
this.service = service;
}
@Override
public void run() {
service.methodWait();
}
}
class ThreadTwo extends Thread {
private Service service;
public ThreadTwo(Service service) {
this.service = service;
}
@Override
public void run() {
service.methodNotify();
}
}
class Run {
public static void main(String[] args) throws Exception {
Service service = new Service();
ThreadOne threadOne = new ThreadOne(service);
threadOne.start();
ThreadTwo threadTwo = new ThreadTwo(service);
threadTwo.start();
}
输出结果
start methodWait -- 1725004815329--Thread-0
立刻停止该线程,释放锁,让其他等等获取该锁的线程执行
start methodNotify -- 1725004815329Thread-1
add次数:0
add次数:1
add次数:2
add次数:3
add次数:4
发出通知停止该线程, 但 notify() 不会立刻停止该线程 当前代码块执全部行结束后,释放锁,让等待的线程获取锁,再执行Thread-1
add次数:5
add次数:6
add次数:7
add次数:8
add次数:9
end methodNotify 这里执行后就释放锁-- 1725004816406--Thread-1
end methodWait -- 1725004816406--Thread-0