呼び出し可能なインターフェイスは、名前から見ることができますが、結果を返すことはできません。 . This return value can be Get it by Future, that is, Future can get the return value of asynchronous execution of tasks. Let's take a simple example below
コードコピーは次のとおりです。
パッケージcom.future.test;
java.io.filenotfoundexceptionをインポートします。
java.io.ioexceptionをインポートします。
java.util.concurrent.callableをインポートします。
java.util.concurrent.executionexceptionをインポートします。
java.util.concurrent.executorserviceをインポートします。
java.util.concurrent.executorsをインポートします。
java.util.concurrent.futuretaskをインポートします。
java.util.concurrent.timeunitをインポートします。
java.util.concurrent.timeoutexceptionをインポートします。
パブリッククラスのmytest {
//実行方法に巻き込まれた例外を受信し、カスタムメソッドが例外をスローします
//プライベート静的スロー可能な例外。
/**
* @param args
*/
public static void main(string [] args){
// TODO自動生成方法スタブ
文字列結果= "";
executorservice executor = executors.newsinglethreadexecutor();
FutureTask <String> Future =
new futureTask <String>(新しいcallable <string>(){// callableインターフェイスをコンストラクターパラメーターとして使用します
public string call(){
//実際のタスクがここで実行されます、ここの戻り値タイプは文字列です。
試す {
thread.sleep(10000);
} catch(arternedexception e){
// TODO自動生成キャッチブロック
//例外= e;
//e.printstacktrace();
}
「11111」を返します。
}});
executor.execute(future);
//ここで他に何でもできます
試す {
result = future.get(5000、timeunit.milliseconds);また、future.get()を使用して、実行タイムアウトを設定せずに結果を取得することもできます。
} catch(arternedexception e){
//system.out.println("taskがキャンセルされました ");
future.cancel(true);
} catch(executionexception e){
future.cancel(true);
} catch(timeoutexception e){
future.cancel(true);
} ついに {
executor.shutdown();
}
System.out.println( "result:"+result);
}
/* public void throwexception()throws filenotfoundexception、ioexception {
if(filenotfoundexceptionの例外インスタンス)
Throw(filenotfoundexception)例外;
if(IOExceptionの例外インスタンス)
スロー(ioException)例外;
}*/
}