没有时间的限制
package org.example.concurrency.test;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* @author huskyui
*/
@Slf4j
public class GuardedObject {
private Object response;
public Object get(){
synchronized (this){
while (response == null){
try{
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return response;
}
}
public void complete(Object response){
synchronized (this){
this.response = response;
this.notifyAll();
}
}
public static void main(String[] args) {
GuardedObject guardedObject = new GuardedObject();
new Thread(()->{
log.info("获取结果");
String response = (String)guardedObject.get();
log.info("结果{}",response);
},"t1").start();
new Thread(()->{
log.info("执行任务");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
guardedObject.complete(new String("hello"));
},"t2").start();
}
}
可以看到线程1在等待线程二的任务结束,后现场一获取结果
设置时间的限制
package org.example.concurrency.test;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* @author huskyui
*/
@Slf4j
public class GuardedObject {
private Object response;
public Object get() {
synchronized (this) {
while (response == null) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return response;
}
}
public Object get(long timeout) {
long begin = System.currentTimeMillis();
long passedTime = 0;
synchronized (this) {
while (response == null) {
long delay = timeout - passedTime;
if (delay <= 0) {
break;
}
try {
this.wait(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
passedTime = System.currentTimeMillis() - begin;
}
return response;
}
}
public void complete(Object response) {
synchronized (this) {
this.response = response;
this.notifyAll();
}
}
public static void main(String[] args) {
GuardedObject guardedObject = new GuardedObject();
// t1线程等待t2线程的结果
new Thread(() -> {
log.info("获取结果");
String response = (String) guardedObject.get(1500);
log.info("结果{}", response);
}, "t1").start();
new Thread(() -> {
log.info("执行任务");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
guardedObject.complete(new String("hello"));
}, "t2").start();
}
}