面试题答案
一键面试设计思路
- 定义自定义线程状态:通过创建一个枚举类型来定义自定义线程状态。
- 添加状态字段到线程类:在自定义线程类中添加一个字段来表示当前自定义状态。
- 实现状态转换方法:编写方法来处理从自定义状态到标准Java线程状态的转换。例如,当自定义状态满足一定条件时,将其转换为
RUNNABLE
或WAITING
等标准状态。
代码实现
public class CustomThread extends Thread {
// 自定义线程状态枚举
public enum CustomState {
CUSTOM_READY,
CUSTOM_PENDING
}
private CustomState customState;
public CustomThread() {
this.customState = CustomState.CUSTOM_READY;
}
public CustomState getCustomState() {
return customState;
}
public void setCustomState(CustomState customState) {
this.customState = customState;
}
// 示例方法:根据自定义状态转换为标准状态
public void transitionToStandardState() {
switch (customState) {
case CUSTOM_READY:
// 这里可以做一些准备工作,然后设置线程为可运行状态
this.setPriority(Thread.NORM_PRIORITY);
break;
case CUSTOM_PENDING:
// 假设这种状态下线程需要等待某个条件满足
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
@Override
public void run() {
// 线程执行逻辑
System.out.println("Thread is running with custom state: " + customState);
}
}
你可以使用以下方式测试上述代码:
public class Main {
public static void main(String[] args) {
CustomThread customThread = new CustomThread();
customThread.setCustomState(CustomThread.CustomState.CUSTOM_PENDING);
customThread.start();
customThread.transitionToStandardState();
}
}