0

我创建了一个从谷歌搜索中找到的可调用布尔值,我想调用它。语法是什么?我找不到任何有用的东西,我有点像新手......不要介意代码它只是一个例子

我想正确检查其他班级是否有活动

public static class HA implements Callable<Boolean> {
    Socket socket1= null;
    Socket socket2= null;
     ...
    public HA (Socket output) {
        client = output;
        clientt = outpu;
    }

    public Boolean call(boolean isActive) throws Exception {
        String stringExample= "";
        String stringExample2= "";
        ...
4

2 回答 2

0

Callable (.call()) 就像 Runnable (.run) 碰巧返回一些东西而不是 void。

如果你在 call() 方法上使用了 @Override 注释,你会看到你没有覆盖它,而是遇到了另一个与 Callable.call() 无关的重载 call(boolean) 方法。

您显然可以自己调用 .call() 方法,但通常这些 Callable 对象出现在将执行委托给 Executor 的上下文中(通常是在另一个线程上运行 tha 调用并返回 Future)。

于 2019-12-25T18:27:55.073 回答
0

您需要使用 Executor 服务来提交 Task

//Get ExecutorService from Executors utility class, thread pool size is 10
ExecutorService executor = Executors.newFixedThreadPool(10);
//create a list to hold the Future object associated with Callable
List<Future<Boolean>> list = new ArrayList<>();
//Create Callable instance
Callable<Boolean> callable = new HA(new Socket());
for(int i=0; i< 100; i++){
    //submit Callable tasks to be executed by thread pool
    Future<Boolean> future = executor.submit(callable);
    //add Future to the list, we can get return value using Future
    list.add(future);
}
for(Future<Boolean> fut : list){
    try {
        //print the return value of Future, notice the output delay in console
        // because Future.get() waits for task to get completed
        System.out.println(new Date()+ "::"+fut.get());
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}
//shut down the executor service now
executor.shutdown();

你的 Callable 可能如下

public static class HA implements Callable<Boolean> {
        private Socket client;
        public HA (Socket output) {
            this.client = output;
        }
        @Override
        public Boolean call() throws Exception {
            Thread.sleep(1000);
            //return the thread name executing this callable task
            return true;
        }
    }
于 2019-12-25T18:08:25.460 回答