面试题答案
一键面试基于Java条件变量处理任务依赖关系的机制
- 定义任务类
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Task {
private final String taskName;
private final Runnable taskAction;
private boolean completed = false;
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
public Task(String taskName, Runnable taskAction) {
this.taskName = taskName;
this.taskAction = taskAction;
}
public void execute() {
lock.lock();
try {
taskAction.run();
completed = true;
condition.signalAll();
} finally {
lock.unlock();
}
}
public void waitForCompletion() {
lock.lock();
try {
while (!completed) {
condition.await();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
}
}
- 处理任务依赖关系
public class TaskScheduler {
public static void main(String[] args) {
Task taskA = new Task("TaskA", () -> {
System.out.println("TaskA is running");
// 模拟任务执行
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("TaskA completed");
});
Task taskB = new Task("TaskB", () -> {
System.out.println("TaskB is running");
// 模拟任务执行
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("TaskB completed");
});
Thread threadA = new Thread(taskA);
Thread threadB = new Thread(() -> {
taskA.waitForCompletion();
taskB.execute();
});
threadA.start();
threadB.start();
}
}
处理任务执行异常
- 在任务类的
execute
方法中捕获异常
public void execute() {
lock.lock();
try {
taskAction.run();
completed = true;
condition.signalAll();
} catch (Exception e) {
System.err.println("Task " + taskName + " failed: " + e.getMessage());
} finally {
lock.unlock();
}
}
- 在依赖任务的执行逻辑中处理异常
Thread threadB = new Thread(() -> {
try {
taskA.waitForCompletion();
taskB.execute();
} catch (Exception e) {
System.err.println("TaskB dependency or execution failed: " + e.getMessage());
}
});
处理任务超时
- 在
waitForCompletion
方法中添加超时机制
public boolean waitForCompletion(long timeout, TimeUnit unit) {
lock.lock();
try {
long endTime = System.nanoTime() + unit.toNanos(timeout);
while (!completed) {
long remainingTime = endTime - System.nanoTime();
if (remainingTime <= 0) {
return false;
}
condition.awaitNanos(remainingTime);
}
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
lock.unlock();
}
}
- 在依赖任务的执行逻辑中使用超时机制
Thread threadB = new Thread(() -> {
if (!taskA.waitForCompletion(5, TimeUnit.SECONDS)) {
System.err.println("TaskA timed out");
} else {
taskB.execute();
}
});
通过上述代码,可以使用Java条件变量设计一套处理任务依赖关系的机制,并有效处理任务执行异常和任务超时的情况。