Java에서 C#의 Func<TResult>, Func<T, bool> 대리자(Delegate) 비슷하게 사용하기
C# 예제
class Program { static void Main(string[] args) { // 1씩 더하다가 10이되면 결과를 반환 int arg = 1; int result = Program.DoUntil(5000, () => { Console.WriteLine(arg); return arg++; }, (r) => r == 10); Console.WriteLine(result); Console.ReadKey(); } // 지정한 시간동안 fnAction의 리턴값이 untilPredicate 함수를 만족시킬 때까지 반복 후 결과값 반환 public static T DoUntil<T>(int timeout, Func<T> fnAction, Func<T, bool> untilPredicate) { var endTime = DateTime.UtcNow.AddMilliseconds(timeout); while (true) { T result = fnAction(); if (untilPredicate(result)) return result; if (DateTime.UtcNow > endTime) throw new System.TimeoutException(); System.Threading.Thread.Sleep(100); } } } |
Android Java 예제
public class Program { public static void main(String[] args) throws Exception { final int arg = 1; int result = Program.DoUntil(5000, new Callable<Integer>() { int arg2 = arg; @Override public Integer call() throws Exception { System.out.println(arg2); return arg2++; } }, new Predicate<Integer>() { @Override public boolean apply(Integer arg) { return (arg == 10); } } ); System.out.println(result); }
public static <T> T DoUntil(int timeout, Callable<T> fnAction, Predicate<T> untilPredicate) throws Exception{ long endTime = System.currentTimeMillis() + timeout; while (true) { T result; result = fnAction.call(); if (untilPredicate.apply(result)) return result; if (System.currentTimeMillis() > endTime) throw new RuntimeException("timed out"); Thread.sleep(100); } } } |
C#의 Func<TResult> Delegate는 Java의 Callable<T>로, Func<T, bool>는 Predicate<T>로 구현할 수 있다.
Java 8이 적용되면 Lambda 구문을 사용할 수 있으나 그 전까지는 위의 방식을 사용함.