一文搞懂java的wait,wait(time),notify(),notifyAll()方法
时间:2021-06-17
object1.wait()方法是释放当前线程获得的object1上的锁,并使当前线程进入等待(WAITING)状态,当其他线程调用object1.notify(),或者object1.notifyAll()方法时,当前线程才能被转换成阻塞(BLOCKED)状态,此时wait()方法不会返回,只是让当前线程参与object1锁的竞争,当当前线程再次竞争获得object1的锁后,wait方法才会返回,当前线程变成可运行状态,然后继续执行wait()后的代码。
object1.wait(time)方法也会释放当前线程获得的object1上的锁,并使当前线程进入计时等待(TIMED_WAITING)状态,它跟wait()方法的区别是就算没有其他线程调用object1.notify()或object1.notifyAll()方法,只要时间time到了后,当前线程自动进入阻塞(BLOCKED)状态,如果时间没到前有其他线程唤醒该进程,则它提前进入阻塞(BLOCKED)状态,参与object1对象锁的竞争,再次获得object1对象锁后wait(time)才返回,当前线程变成可运行状态,然后继续执行wait(time)后的代码。
object1.notify() 方法是从object1对象的等待线程中随机选择一个线程唤醒,使其进入阻塞(BLOCKED)状态(它可以参与竞争获取object1对象锁)
object1.notifyAll() 方法是把object1对象的所有等待线程唤醒,使他们全部进入阻塞(BLOCKED)状态(他们都可以参与竞争获取object1对象锁)
public class ThreadWaitTest { public static void main(String[] args) { System.out.println("begin ..."); try { Thread thread1 = new Thread(new ThreadWait(), "thread1"); Thread thread2 = new Thread(new ThreadWait(), "thread2======"); Thread thread3 = new Thread(new ThreadWait(), "thread3============"); thread1.start(); thread2.start(); thread3.start(); } catch (Exception e) { e.printStackTrace(); } System.out.println("ended"); } } class ThreadWait implements Runnable { static Object lock = new Object(); int count = 0; @Override public void run() { System.out.println(Thread.currentThread().getName() + " begin run!"); count(); } public void count() { while (count < 50) { synchronized (lock) { System.out.println(Thread.currentThread().getName() + " : count = " + count); try { count++; int time = 300; long begin = System.currentTimeMillis(); if (Thread.currentThread().getName().equals("thread1")) { System.out.println(Thread.currentThread().getName() + " wait " + time + " begin " + begin); lock.wait(time); System.out.println(Thread.currentThread().getName() + " wait " + time + " end " + (System.currentTimeMillis() - begin)); break; } Thread.sleep(10); lock.wait(100); } catch (Exception e) { e.printStackTrace(); } // lock.notifyAll(); } } } }