park()=wait() unpark()=notifly
3种让线程等待和唤醒的方法
java 传统阻塞与唤醒
package com.ge.healthcare.cn.apm.gateway.util;
public class LockSupportDemo {
static Object objectLock = new Object();
public static void main(String[] args) {
new Thread(()->{
synchronized (objectLock){
System.out.println(Thread.currentThread().getName()+" --------come in");
try {
objectLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" -----------------被唤醒");
}
},"A").start();
new Thread(()->{
synchronized (objectLock){
objectLock.notify();
System.out.println(Thread.currentThread().getName()+" ------------通知");
}
},"B").start();
}
}
注意
Lock方式阻塞与唤醒
package com.ge.healthcare.cn.apm.gateway.util;
import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;
public class LockSupportDemo {
static Object objectLock = new Object();
static Lock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public static void main(String[] args) {
new Thread(()->{
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"----------come in");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"----------被唤醒");
} finally {
lock.unlock();
}
},"A").start();
new Thread(()->{
lock.lock();
try {
condition.signal();
System.out.println(Thread.currentThread().getName()+"----------通知");
} finally {
lock.unlock();
}
},"B").start();
}
}
LockSupport通知与唤醒 unpark可以在park之前执行,前面两个例子不行。
package com.ge.healthcare.cn.apm.gateway.util;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
public class LockSupportDemo {
static Object objectLock = new Object();
static Lock lock = new ReentrantLock();
static Condition condition = lock.newCondition();
public static void main(String[] args) {
Thread a = new Thread(()->{
System.out.println(Thread.currentThread().getName()+"--------------come in");
LockSupport.park();//被阻塞....等待通知放行,它要通过时需要许可证
System.out.println(Thread.currentThread().getName()+"--------------被唤醒");
},"a");
a.start();
try {TimeUnit.SECONDS.sleep(3L);} catch (InterruptedException e) { e.printStackTrace();}
Thread b = new Thread(()->{
LockSupport.unpark(a);
System.out.println(Thread.currentThread().getName()+"--------------通知了");
},"b");
b.start();
}
}