package com.study.controller;
public class TestObjectWait {
public static void main(String[] args) {
final Object lock = new Object();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "拿到锁了");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到信号");
System.out.println(Thread.currentThread().getName() + "释放锁");
}
}
}, "线程1").start();
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "先不拿锁,sleep 3000");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "拿到锁了");
try {
System.out.println(Thread.currentThread().getName() + "拿到锁后,sleep 3000");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "发出信号");
lock.notifyAll();
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + "发出信后,sleep 3000");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "释放锁");
}
}
}, "线程2").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "拿到锁了");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到信号");
System.out.println(Thread.currentThread().getName() + "释放锁");
}
}
}, "线程3").start();
}
}
java object wait notify 学习
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 简书:capo 转载请注明原创出处,谢谢! 前言: 今天,我们讲讲Object中wait和notify/not...
- 在java多线程中可以使用object.wait/notify来进行线程之间的通讯 wait会使当前线程进入等待状...
- Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言。Java 技术具有卓越的通用性、高效性、平台移植性和...
- 1.使用注意点 (1)调用wait(),notify()和notifyAll()时需要先对调用对象加锁。(2)调用...