change: 丰富测试用例; 并发性状态机CAS默认触发状态处理器.

This commit is contained in:
2025-04-15 16:47:47 +08:00
parent 89799257aa
commit 961a496465
3 changed files with 25 additions and 2 deletions

View File

@@ -13,7 +13,7 @@ public interface ConcurrentStateMachine<S> extends StateMachine<S> {
/**
* 尝试使用CAS更新状态
* <li> 无论是否成功更新都不触发状态处理器
* <li> 成功更新触发状态处理器
*
* @param expectedValue 前置状态
* @param newValue 更新的状态值

View File

@@ -41,7 +41,7 @@ public class DefaultConcurrentStateMachine<S> extends AbstractStateMachine<S> im
@Override
public boolean compareAndSet(S expectedValue, S newValue) {
return compareAndSet(expectedValue, newValue, false);
return compareAndSet(expectedValue, newValue, true);
}
@Override

View File

@@ -7,6 +7,9 @@ import com.serliunx.statemanagement.support.PrinterEvent;
import com.serliunx.statemanagement.support.PrinterState;
import org.junit.Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 状态机测试
*
@@ -16,6 +19,8 @@ import org.junit.Test;
*/
public class MachineTest {
private final ExecutorService executor = Executors.newFixedThreadPool(5);
@Test
public void testStandardStateMachine() throws Exception {
StateMachine<PrinterState> stateMachine = StateMachineBuilder.from(PrinterState.values())
@@ -46,4 +51,22 @@ public class MachineTest {
System.out.println(stateMachine.current());
stateMachine.close();
}
@Test
public void testConcurrentStateMachine2() throws Exception {
ConcurrentStateMachine<PrinterState> stateMachine = StateMachineBuilder.from(PrinterState.values())
.async(false)
.concurrent()
.whenEntry(PrinterState.STOPPING, h -> {
System.out.println("entering stopping...");
})
.build();
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
System.out.println(stateMachine.compareAndSet(PrinterState.IDLE, PrinterState.STOPPING, true));
});
}
}
}