wait notify方式
package org.example.concurrency.test;
import lombok.extern.slf4j.Slf4j;
/**
* @author huskyui
*/
@Slf4j
public class Test28 {
static final Object lock = new Object();
static boolean t2Runned = false;
public static void main(String[] args) {
Thread t1 = new Thread(()->{
synchronized (lock){
while (!t2Runned){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (t2Runned){
log.debug("t1");
}else{
log.debug("not t1");
}
}
});
Thread t2 = new Thread(()->{
synchronized (lock){
t2Runned = true;
log.debug("t2");
lock.notify();
}
});
t1.start();
t2.start();
}
}
park unpark
package org.example.concurrency.test;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.LockSupport;
/**
* @author huskyui
*/
@Slf4j
public class Test29 {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
LockSupport.park();
log.debug("t1");
});
t1.start();
Thread t2 = new Thread(()->{
log.debug("t2");
LockSupport.unpark(t1);
});
t2.start();
}
}