本文主要是介绍【JUC】08-线程等待与唤醒,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. Object wait和notify实现等待与唤醒
没有锁会报错。
public class demo01 {public static void main(String[] args) {Object objectLock = new Object();new Thread(()->{synchronized (objectLock) {try {// 释放当前锁, 等待notify, 必须先使用wait才能使用notifyobjectLock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("Thread 1");}}).start();new Thread(()->{synchronized (objectLock) {System.out.println("Thread 2");objectLock.notify();}}).start();}
}
2. Lock.newCondition await和signal实现等待与唤醒
public class demo02 {public static void main(String[] args) {Lock lock = new ReentrantLock();Condition condition = lock.newCondition();new Thread(()->{lock.lock();try {// 释放锁并等待通知condition.await();System.out.println("Thread 1");} catch (InterruptedException e) {throw new RuntimeException(e);} finally {lock.unlock();}}).start();new Thread(()->{lock.lock();System.out.println("Thread 2");condition.signal();lock.unlock();}).start();}
}
3. LockSupport park和unpark实现等待与唤醒
unpark只能产生一个permit,且可以提前产生,
public class demo03 {public static void main(String[] args) {Thread thread = new Thread(() -> {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}// 可以先进行 unpark, 并且 permit 只能有一个// 需要两个permitLockSupport.park();LockSupport.park();System.out.println("Thread1");});thread.start();new Thread(()->{System.out.println("Thread 2");// 只会产生一个permitLockSupport.unpark(thread);LockSupport.unpark(thread);}).start();}
}
这篇关于【JUC】08-线程等待与唤醒的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!