import java.util.concurrent.TimeUnit;
public class Test4 {
public static void main(String[] args) throws InterruptedException {
Object object = new Object();
new Thread(()->{
synchronized (object){
System.out.println(Thread.currentThread().getName()+"------ come in");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"------ 被唤醒");
}
},"t1").start();
TimeUnit.SECONDS.sleep(5);
new Thread(()->{
synchronized (object){
System.out.println(Thread.currentThread().getName()+"------ come in");
object.notify();
System.out.println(Thread.currentThread().getName()+"------ come out");
}
},"t2").start();
}
}
t1------ come in
t2------ come in
t2------ come out
t1------ 被唤醒
wait 和notify 方法必须放在同步方法里,且成对出现
先wait 然后notify 才Ok
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test5 {
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(()->{
lock.lock();
System.out.println(Thread.currentThread().getName()+"------ come in");
try {
condition.await();
System.out.println(Thread.currentThread().getName()+"------ 被唤醒");
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
lock.unlock();
}
},"t1").start();
TimeUnit.SECONDS.sleep(2);
new Thread(()->{
lock.lock();
try {
condition.signal();
System.out.println(Thread.currentThread().getName()+"------ 被唤醒");
}
finally {
lock.unlock();
}
},"t2").start();
}
}
线程先要获得必须持有锁,必须在锁块中
先等待在唤醒
import java.util.concurrent.locks.LockSupport;
public class Test6 {
public static void main(String[] args) {
Thread t1 = new Thread((
) -> {
System.out.println(Thread.currentThread().getName()+"------ come in");
LockSupport.park();
System.out.println(Thread.currentThread().getName()+"------ come out");
}, "t1");
t1.start();
Thread t2 = new Thread((
) -> {
LockSupport.unpark(t1);
System.out.println(Thread.currentThread().getName()+"------ 发送通知");
}, "t2");
t2.start();
}
}
无锁要求
唤醒和等待可以交换位置,不影响功能。