notify()方法唤醒处于等待的线程 谁先等待即谁先调用wait()就唤醒谁
测试案例:
四个类
MyService.class 方法类
MyThreadA.class 等待线程类
MyThreadB.clsss 唤醒线程类
Test.class 测试线程类
MyService.class
public class MyService {
private Object lock = new Object();
public void waitMethod() {
try {
synchronized (lock) {
System.out.println("begin wait "+System.currentTimeMillis()+
" " + Thread.currentThread().getName());
lock.wait();
System.out.println("end wait "+System.currentTimeMillis()+
" " + Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void notifyMethod() {
synchronized (lock) {
System.out.println("begin notify " + System.currentTimeMillis()+" "
+ Thread.currentThread().getName());
lock.notify();
System.out.println("end notify " + System.currentTimeMillis()+" "
+ Thread.currentThread().getName());
}
}
}
MyThreadA.class
public class MyThreadA extends Thread {
private MyService service;
public MyThreadA(MyService service) {
this.service = service;
}
@Override
public void run() {
service.waitMethod();
}
}
MyThreadB.clsss
public class MyThreadB extends Thread {
private MyService service;
public MyThreadB(MyService service) {
this.service = service;
}
@Override
public void run() {
service.notifyMethod();
}
}
Test.class
public class Test {
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
for (int i = 0; i < 10; i++) {
MyThreadA myThreadA = new MyThreadA(myService);
myThreadA.start();
}
Thread.sleep(1000);
MyThreadB t1 = new MyThreadB(myService);
t1.start();
Thread.sleep(500);
MyThreadB t2 = new MyThreadB(myService);
t2.start();
Thread.sleep(500);
MyThreadB t3 = new MyThreadB(myService);
t3.start();
Thread.sleep(500);
MyThreadB t4 = new MyThreadB(myService);
t4.start();
Thread.sleep(500);
MyThreadB t5 = new MyThreadB(myService);
t5.start();
}
}
运行结果
// 开启10个等待线程
begin wait 1627727828285 Thread-0
begin wait 1627727828286 Thread-2
begin wait 1627727828286 Thread-3
begin wait 1627727828286 Thread-1
begin wait 1627727828286 Thread-4
begin wait 1627727828287 Thread-5
begin wait 1627727828287 Thread-6
begin wait 1627727828287 Thread-7
begin wait 1627727828287 Thread-8
begin wait 1627727828288 Thread-9
// 第一个唤醒线程
begin notify 1627727829290 Thread-10
end notify 1627727829290 Thread-10
end wait 1627727829290 Thread-0 // 由这行可以看出唤醒的是Thread-0
begin notify 1627727829789 Thread-11
end notify 1627727829789 Thread-11
end wait 1627727829789 Thread-2 // 由这行可以看出唤醒的是Thread-2
begin notify 1627727830290 Thread-12
end notify 1627727830290 Thread-12
end wait 1627727830290 Thread-3 // 由这行可以看出唤醒的是Thread-3
begin notify 1627727830791 Thread-13
end notify 1627727830791 Thread-13
end wait 1627727830791 Thread-1 // 由这行可以看出唤醒的是Thread-1
begin notify 1627727831292 Thread-14
end notify 1627727831292 Thread-14
end wait 1627727831292 Thread-4 // 由这行可以看出唤醒的是Thread-4
唤醒顺序完全符合调用wait()方法的顺序