我有一个启动多个线程的类,这些线程都运行while(true)
循环。在测试运行了一定时间后,是否有可能对测试的状态使用Assert
语句?
如果未通过测试,则超时功能将工作。
这是一个人为的例子来说明我正在尝试做什么。测试在底部。
class RunProgram {
private DataClass dataClass = new DataClass();
private Thread1 thread1 = new Thread1(dataClass);
void startThis() {
ExecutorService pool = Executors.newFixedThreadPool(5);
try {
pool.execute(thread1);//Thread 1
//... more threads with while loops
runMainThread(dataClass);
} finally {
pool.shutdown();
}
}
void runMainThread(DataClass data1){
while(true){
dataClass.setInternalDataInt(20);
//do stuff
}
}
public Thread1 getThread1(){
return this.thread1;
}
}
class Thread1 implements Runnable{
private DataClass dataClass;
Thread1(DataClass dataClass){
this.dataClass = dataClass;
}
public void run() {
dataClass.setInternalDataInt(10);
while (true) {
//dostuff
}
}
public DataClass getDataClass(){
return dataClass;
}
public void setDataClass(DataClass dataClass){
this.dataClass = dataClass;
}
}
class DataClass {
private int internalDataInt;
public int getInternalDataInt(){
return this.internalDataInt;
}
public void setInternalDataInt(int internalDataInt){
this.internalDataInt = internalDataInt;
}
}
class Tests{
@Test
public void stateOfThread1() {
RunProgram runProgram = new RunProgram();
runProgram.startThis();
//Run above for 100 millisecond and then end
Assertions.assertEquals(runProgram.getThread1().getDataClass().getInternalDataInt(), 20);
}
}
1条答案
按热度按时间g0czyy6m1#
找到我要找的东西了。
使用ScheduledExecutorService(计划执行程序服务):
一个ExecutorService,可以调度命令在给定延迟后运行,或定期执行。