嗨,我是并发的新手所以我写了一个非常基本的程序,看看是否在线程完成future.isDone()方法显示为true,不幸的是,当我使用scheduledAtFixedRate方法安排任务时,它总是显示“false” 。但是,如果我使用schedule方法它显示“true”,当然简单任务不会在几秒钟后重新运行。任何建议或解释,以帮助我理解为什么会出现这种情况将非常感激。
谢谢!
这里有代码:
package com.company;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
Main mn = new Main();
System.out.println("Main thread started...");
mn.runobjects();
System.out.println("Main thread stopping...");
}
@Test
public void runobjects(){
List<commonrun> Obj = new ArrayList<>();
Obj.add(new TestObj1());
Obj.add(new TestObj2());
Obj.add(new TestObj3());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
ScheduledFuture<?> futures1 = null;
ScheduledFuture<?> futures2 = null;
ScheduledFuture<?> futures3 = null;
int i=0;
for (commonrun obj : Obj){
if (i==0) {
futures1 = executor.schedule(() -> obj.runme(), 0, TimeUnit.SECONDS);
}
if (i==1) {
futures2 = executor.scheduleAtFixedRate(() -> obj.runme(), 0, 10, TimeUnit.SECONDS);
}
if (i==2) {
futures3 = executor.scheduleAtFixedRate(() -> obj.runme(), 0, 10, TimeUnit.SECONDS);
}
i++;
}
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 is done : "+ futures1.isDone());
System.out.println("Thread 2 is done : "+ futures2.isDone());
System.out.println("Thread 3 is done : "+ futures3.isDone());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package com.company;
public interface commonrun {
public void runme();
}
package com.company;
public class TestObj1 implements commonrun {
static int counter = 0;
@Override
public void runme() {
System.out.println("Object 1 Starting... run : " + counter);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Object 1 Stopping... run : " + counter);
counter++;
}
}
package com.company;
public class TestObj2 implements commonrun {
@Override
public void runme() {
System.out.println("Object 2 Starting...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Object 2 Stopping...");
}
}
package com.company;
public class TestObj3 implements commonrun {
@Override
public void runme() {
System.out.println("Object 3 Starting...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Object 3 Stopping...");
}
}
答案 0 :(得分:1)
ScheduledExecutorService.scheduleAtFixedRate()
安排重复性任务。它永远不会(自然地)完成,所以它不会完成。从方法的文档:
任务只会通过取消或终止来终止 执行
因此,只有当您致电future.cancel()
或executor.terminate()
时,任务才会完成 ,future.isDone()
将返回true
。
虽然在第一个任务的执行完成后,人们可能会期望future
变为已完成,但由于以下原因,情况并非如此:
isDone
无法报告重复作业的当前执行状态