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();
}
}
网友评论