当前位置: 首页>>代码示例>>Java>>正文


Java RunnableFuture类代码示例

本文整理汇总了Java中java.util.concurrent.RunnableFuture的典型用法代码示例。如果您正苦于以下问题:Java RunnableFuture类的具体用法?Java RunnableFuture怎么用?Java RunnableFuture使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


RunnableFuture类属于java.util.concurrent包,在下文中一共展示了RunnableFuture类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: newTaskFor

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
/**
 * Returns a {@code RunnableFuture} for the given runnable and default
 * value.
 *
 * @param runnable the runnable task being wrapped
 * @param value    the default value for the returned future
 * @return a {@code RunnableFuture} which, when run, will run the
 * underlying runnable and which, as a {@code Future}, will yield
 * the given value as its result and provide for cancellation of
 * the underlying task
 * @since 1.6
 */
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value)
{
    if (runnable instanceof CancellableRunnable)
    {
        return new FutureTask<T>(runnable, value)
        {
            @Override
            public boolean cancel(boolean mayInterruptIfRunning)
            {
                boolean return_value = super.cancel(mayInterruptIfRunning);
                CancellableRunnable.class.cast(runnable).cancelTask();
                return return_value;
            }
        };
    }
    else
    {
        return super.newTaskFor(runnable, value);
    }
}
 
开发者ID:Tostino,项目名称:pgAutomator-agent,代码行数:34,代码来源:ThreadFactory.java

示例2: resolve

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
@Override
public java.util.concurrent.Future<ProjectProblemsProvider.Result> resolve() {
    ProjectProblemsProvider.Result res;
    if (action != null) {
        action.actionPerformed(null);
        String text = (String) action.getValue(ACT_START_MESSAGE);
        if (text != null) {
            res = ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.RESOLVED, text);
        } else {
            res = ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.RESOLVED);
        }
    } else {
        res = ProjectProblemsProvider.Result.create(ProjectProblemsProvider.Status.UNRESOLVED, "No resolution for the problem");
    }
    RunnableFuture<ProjectProblemsProvider.Result> f = new FutureTask(new Runnable() {
        @Override
        public void run() {
        }
    }, res);
    f.run();
    return f;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:JUnitProjectOpenedHook.java

示例3: submit

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
public synchronized void submit(final RunnableFuture task, long delay)
{
   getTimer().schedule(new TimerTask()
      {
         @Override
         public void run()
         {
            Thread t = new Thread(new Runnable()
               {
                  @Override
                  public void run()
                  {
                     submit(task);
                  }
               });
            t.setDaemon(daemon);
            t.start();
         }
      }, delay);
}
 
开发者ID:wellsb1,项目名称:fort_j,代码行数:21,代码来源:Executor.java

示例4: put

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
void put(RunnableFuture task)
{
   synchronized (queue)
   {
      while (queue.size() >= queueMax)
      {
         try
         {
            queue.wait();
         }
         catch (Exception ex)
         {

         }
      }
      queue.add(task);
      queue.notifyAll();
   }
}
 
开发者ID:wellsb1,项目名称:fort_j,代码行数:20,代码来源:Executor.java

示例5: take

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
RunnableFuture take()
{
   RunnableFuture t = null;
   synchronized (queue)
   {
      while (queue.size() == 0)
      {
         try
         {
            queue.wait();
         }
         catch (InterruptedException ex)
         {

         }
      }

      t = queue.removeFirst();
      queue.notifyAll();
   }
   return t;
}
 
开发者ID:wellsb1,项目名称:fort_j,代码行数:23,代码来源:Executor.java

示例6: submitRequest

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
/**
 * 客户端使用本方法提交一个绑定到指定tag的任务,不同情况下可以根据tag取消任务
 *
 * @param requestId
 * @param task
 * @return
 */
public synchronized void submitRequest(String requestId, RequestManager.RequestRunnable task) {
    //执行同步操作
    RunnableFuture<String> future = newTaskFor(task, requestId);
    if (!TextUtils.isEmpty(requestId)) {
        List<Future<String>> futures = mFutures.get(requestId);
        if (futures == null) {
            futures = new ArrayList<>();
            mFutures.put(requestId, futures);
        }
        futures.add(future);
        mRequests.put(future, task.getRequest());
    }

    //执行异步任务
    execute(future);


}
 
开发者ID:jessie345,项目名称:RetrofitAppArchitecture,代码行数:26,代码来源:RequestExecutor.java

示例7: init

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
/**
 * Initial MiniDownloader.
 *
 * @param context
 */
public void init(Context context) {
    this.appContext = context.getApplicationContext();
    /** Create work executor. */
    this.workExecutor = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors(), 0L, TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>()) {
        @Override
        protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
            if (callable instanceof CustomFutureCallable) {
                return ((CustomFutureCallable) callable).newTaskFor();
            }
            return super.newTaskFor(callable);
        }
    };
    /** Create command executor. */
    this.commandExecutor = Executors.newSingleThreadExecutor();
    /** Create and initial task manager. */
    taskManager = new TaskManager();
    taskManager.init(context);
    /** Create and start ProgressUpdater. */
    progressUpdater = new ProgressUpdater();
    progressUpdater.start();
}
 
开发者ID:xyhuangjinfu,项目名称:MiniDownloader,代码行数:27,代码来源:MiniDownloader.java

示例8: writeDirectory

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
public static PsiDirectory writeDirectory(PsiDirectory dir, DirectoryWrapper dirWrapper, Project project) {
    if (dir == null) {
        //todo print error
        return null;
    }

    RunnableFuture<PsiDirectory> runnableFuture = new FutureTask<>(() ->
            ApplicationManager.getApplication().runWriteAction(new Computable<PsiDirectory>() {
                @Override
                public PsiDirectory compute() {
                    return writeDirectoryAction(dir, dirWrapper, project);
                }
            }));

    ApplicationManager.getApplication().invokeLater(runnableFuture);

    try {
        return runnableFuture.get();
    } catch (InterruptedException | ExecutionException e) {
        Logger.log("runnableFuture  " + e.getMessage());
        Logger.printStack(e);
    }

    return null;
}
 
开发者ID:CeH9,项目名称:PackageTemplates,代码行数:26,代码来源:FileWriter.java

示例9: submit

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
/**
 * 客户端使用本方法提交一个绑定到指定tag的任务,不同情况下可以根据tag取消任务
 *
 * @param tag
 * @param task
 * @return
 */
public synchronized void submit(String tag, Runnable task) {
    //执行同步操作
    RunnableFuture<String> future = newTaskFor(task, tag);
    if (!TextUtils.isEmpty(tag)) {
        List<Future<String>> list = mFutures.get(tag);
        if (list == null) {
            list = new ArrayList<>();
            mFutures.put(tag, list);
        }
        list.add(future);
    }

    //执行异步任务
    execute(future);


}
 
开发者ID:jessie345,项目名称:RealArchitecture,代码行数:25,代码来源:RequestExecutor.java

示例10: testDismissingSnapshotNotRunnable

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
@Test
public void testDismissingSnapshotNotRunnable() throws Exception {
	setupRocksKeyedStateBackend();
	try {
		RunnableFuture<KeyedStateHandle> snapshot =
			keyedStateBackend.snapshot(0L, 0L, testStreamFactory, CheckpointOptions.forCheckpoint());
		snapshot.cancel(true);
		Thread asyncSnapshotThread = new Thread(snapshot);
		asyncSnapshotThread.start();
		try {
			snapshot.get();
			fail();
		} catch (Exception ignored) {

		}
		asyncSnapshotThread.join();
		verifyRocksObjectsReleased();
	} finally {
		this.keyedStateBackend.dispose();
		this.keyedStateBackend = null;
	}
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:23,代码来源:RocksDBStateBackendTest.java

示例11: testCompletingSnapshot

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
@Test
public void testCompletingSnapshot() throws Exception {
	setupRocksKeyedStateBackend();
	try {
		RunnableFuture<KeyedStateHandle> snapshot =
			keyedStateBackend.snapshot(0L, 0L, testStreamFactory, CheckpointOptions.forCheckpoint());
		Thread asyncSnapshotThread = new Thread(snapshot);
		asyncSnapshotThread.start();
		waiter.await(); // wait for snapshot to run
		waiter.reset();
		runStateUpdates();
		blocker.trigger(); // allow checkpointing to start writing
		waiter.await(); // wait for snapshot stream writing to run
		KeyedStateHandle keyedStateHandle = snapshot.get();
		assertNotNull(keyedStateHandle);
		assertTrue(keyedStateHandle.getStateSize() > 0);
		assertEquals(2, keyedStateHandle.getKeyGroupRange().getNumberOfKeyGroups());
		assertTrue(testStreamFactory.getLastCreatedStream().isClosed());
		asyncSnapshotThread.join();
		verifyRocksObjectsReleased();
	} finally {
		this.keyedStateBackend.dispose();
		this.keyedStateBackend = null;
	}
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:26,代码来源:RocksDBStateBackendTest.java

示例12: discardStateFuture

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
/**
 * Discards the given state future by first trying to cancel it. If this is not possible, then
 * the state object contained in the future is calculated and afterwards discarded.
 *
 * @param stateFuture to be discarded
 * @throws Exception if the discard operation failed
 */
public static void discardStateFuture(RunnableFuture<? extends StateObject> stateFuture) throws Exception {
	if (null != stateFuture) {
		if (!stateFuture.cancel(true)) {

			try {
				// We attempt to get a result, in case the future completed before cancellation.
				StateObject stateObject = FutureUtil.runIfNotDoneAndGet(stateFuture);

				if (null != stateObject) {
					stateObject.discardState();
				}
			} catch (CancellationException | ExecutionException ex) {
				LOG.debug("Cancelled execution of snapshot future runnable. Cancellation produced the following " +
					"exception, which is expected an can be ignored.", ex);
			}
		}
	}
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:26,代码来源:StateUtil.java

示例13: testCorrectClassLoaderUsedOnSnapshot

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testCorrectClassLoaderUsedOnSnapshot() throws Exception {

	AbstractStateBackend abstractStateBackend = new MemoryStateBackend(4096);

	final Environment env = createMockEnvironment();
	OperatorStateBackend operatorStateBackend = abstractStateBackend.createOperatorStateBackend(env, "test-op-name");

	AtomicInteger copyCounter = new AtomicInteger(0);
	TypeSerializer<Integer> serializer = new VerifyingIntSerializer(env.getUserClassLoader(), copyCounter);

	// write some state
	ListStateDescriptor<Integer> stateDescriptor = new ListStateDescriptor<>("test", serializer);
	ListState<Integer> listState = operatorStateBackend.getListState(stateDescriptor);

	listState.add(42);

	CheckpointStreamFactory streamFactory = abstractStateBackend.createStreamFactory(new JobID(), "testOperator");
	RunnableFuture<OperatorStateHandle> runnableFuture =
		operatorStateBackend.snapshot(1, 1, streamFactory, CheckpointOptions.forCheckpoint());
	FutureUtil.runIfNotDoneAndGet(runnableFuture);

	// make sure that the copy method has been called
	assertTrue(copyCounter.get() > 0);
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:27,代码来源:OperatorStateBackendTest.java

示例14: testSnapshotEmpty

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
@Test
public void testSnapshotEmpty() throws Exception {
	final AbstractStateBackend abstractStateBackend = new MemoryStateBackend(4096);

	final OperatorStateBackend operatorStateBackend =
			abstractStateBackend.createOperatorStateBackend(createMockEnvironment(), "testOperator");

	CheckpointStreamFactory streamFactory =
			abstractStateBackend.createStreamFactory(new JobID(), "testOperator");

	RunnableFuture<OperatorStateHandle> snapshot =
			operatorStateBackend.snapshot(0L, 0L, streamFactory, CheckpointOptions.forCheckpoint());

	OperatorStateHandle stateHandle = FutureUtil.runIfNotDoneAndGet(snapshot);
	assertNull(stateHandle);
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:17,代码来源:OperatorStateBackendTest.java

示例15: createOperatorStateBackend

import java.util.concurrent.RunnableFuture; //导入依赖的package包/类
@Override
public OperatorStateBackend createOperatorStateBackend(Environment env, String operatorIdentifier) throws Exception {
	return new DefaultOperatorStateBackend(
		env.getUserClassLoader(),
		env.getExecutionConfig(),
		true) {
		@Override
		public RunnableFuture<OperatorStateHandle> snapshot(
			long checkpointId,
			long timestamp,
			CheckpointStreamFactory streamFactory,
			CheckpointOptions checkpointOptions) throws Exception {

			throw new Exception("Sync part snapshot exception.");
		}
	};
}
 
开发者ID:axbaretto,项目名称:flink,代码行数:18,代码来源:TaskCheckpointingBehaviourTest.java


注:本文中的java.util.concurrent.RunnableFuture类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。