本文整理汇总了Java中java.util.concurrent.ThreadPoolExecutor.submit方法的典型用法代码示例。如果您正苦于以下问题:Java ThreadPoolExecutor.submit方法的具体用法?Java ThreadPoolExecutor.submit怎么用?Java ThreadPoolExecutor.submit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.ThreadPoolExecutor
的用法示例。
在下文中一共展示了ThreadPoolExecutor.submit方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: setUp
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
@BeforeExperiment void setUp() throws Exception {
executorService = new ThreadPoolExecutor(NUM_THREADS,
NUM_THREADS,
Long.MAX_VALUE,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1000));
executorService.prestartAllCoreThreads();
final AtomicInteger integer = new AtomicInteger();
// Execute a bunch of tasks to ensure that our threads are allocated and hot
for (int i = 0; i < NUM_THREADS * 10; i++) {
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError =
executorService.submit(
new Runnable() {
@Override
public void run() {
integer.getAndIncrement();
}
});
}
}
示例2: main
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
public static void main(String[] args) {
ThreadPoolExecutor ex = new ThreadPoolExecutor(0, 5, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));
ex.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
ex.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
}
示例3: multiThreadUpload
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
private ThreadPoolExecutor multiThreadUpload(int threadNum, final int threadFileNum) {
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadNum);
pool.prestartAllCoreThreads();
for (int i = 0; i < threadNum; ++i) {
final int threadId = i;
pool.submit(new Runnable() {
@Override
public void run() {
uploadAndDownloadPerform(threadId, threadFileNum);
}
});
}
pool.shutdown();
return pool;
}
示例4: setUp
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
@BeforeExperiment void setUp() throws Exception {
executorService = new ThreadPoolExecutor(NUM_THREADS,
NUM_THREADS,
Long.MAX_VALUE,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1000));
executorService.prestartAllCoreThreads();
final AtomicInteger integer = new AtomicInteger();
// Execute a bunch of tasks to ensure that our threads are allocated and hot
for (int i = 0; i < NUM_THREADS * 10; i++) {
executorService.submit(new Runnable() {
@Override public void run() {
integer.getAndIncrement();
}
});
}
}
示例5: rejectedExecution
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
@Override
public void rejectedExecution(final Runnable runnable, final ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
final Runnable lastTask = getLastElement(executor.getQueue());
if (lastTask == null) {
throw new IllegalStateException("ThreadPoolExecutor should not be full while queue is empty.");
}
executor.remove(lastTask);
executor.submit(runnable);
}
示例6: testJedisClusterRunsWithMultithreaded
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
@Test
public void testJedisClusterRunsWithMultithreaded() throws InterruptedException,
ExecutionException, IOException {
Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>();
jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379));
final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_CONFIG);
jc.set("foo", "bar");
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
List<Future<String>> futures = new ArrayList<Future<String>>();
for (int i = 0; i < 50; i++) {
executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// FIXME : invalidate slot cache from JedisCluster to test
// random connection also does work
return jc.get("foo");
}
});
}
for (Future<String> future : futures) {
String value = future.get();
assertEquals("bar", value);
}
jc.close();
}
示例7: mark
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
/**
* Marks all of the submissions.
* @param threads The thread-pool size to use in marking the assignments
*/
public void mark(final int threads)
throws Exception {
final ProgressBar pb = new ProgressBar("Marking", this.submissions.size());
pb.start();
final CountDownLatch latch = new CountDownLatch(this.submissions.size());
final ThreadPoolExecutor executor = new ThreadPoolExecutor(
threads,
threads,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(threads),
new ThreadPoolExecutor.CallerRunsPolicy()
);
for (Submission s : this.submissions) {
executor.submit(() -> {
try {
s.results(this.markingResults(s.directory()));
pb.step();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
latch.countDown();
}
});
}
executor.shutdown();
latch.await();
pb.stop();
}
示例8: test
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
public void test(int nTasks, int nParallel) {
for(int i=0; i<nTasks; i++) {
System.err.println(i);
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(nParallel);
pool.prestartAllCoreThreads();
for(int k=0; k<nParallel; k++) pool.submit(new Task());
try { waitComplete(); }
catch(Exception e) { e.printStackTrace(); }
pool.shutdown();
}
}
示例9: load
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
@Override
public void load() {
logger.info("Beginning the creation of VP tables.");
if (this.properties_names == null){
logger.error("Properties not calculated yet. Extracting them");
this.properties_names = extractProperties();
}
Vector<TableStats> tables_stats = new Vector<TableStats>();
ThreadPoolExecutor loaders_pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(max_parallelism);
for(int i = 0; i < this.properties_names.length; i++){
String property = this.properties_names[i];
Dataset<Row> table_VP = spark.sql("SELECT s AS s, o AS o FROM tripletable WHERE p='" + property + "'");
String table_name_VP = "vp_" + this.getValidHiveName(property);
loaders_pool.submit(new Thread(() -> {
// save the table
table_VP.write().mode(SaveMode.Overwrite).saveAsTable(table_name_VP);
// calculate stats
if(computeStatistics)
tables_stats.add(calculate_stats_table(table_VP, this.getValidHiveName(property)));
logger.info("Created VP table for the property: " + property);
}));
}
// save the stats in a file with the same name as the output database
if(computeStatistics)
save_stats(this.database_name, tables_stats);
logger.info("Vertical Partitioning completed. Loaded " + String.valueOf(this.properties_names.length) + " tables.");
}
示例10: main
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
/**
* Main method of the class
* @param args
*/
public static void main(String[] args) {
// Create an executor
ThreadPoolExecutor executor=(ThreadPoolExecutor)Executors.newCachedThreadPool();
// Create a task
Task task=new Task();
System.out.printf("Main: Executing the Task\n");
// Send the task to the executor
Future<String> result=executor.submit(task);
// Sleep during two seconds
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cancel the task, finishing its execution
System.out.printf("Main: Cancelling the Task\n");
result.cancel(true);
// Verify that the task has been cancelled
System.out.printf("Main: Cancelled: %s\n",result.isCancelled());
System.out.printf("Main: Done: %s\n",result.isDone());
// Shutdown the executor
executor.shutdown();
System.out.printf("Main: The executor has finished\n");
}
示例11: test
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
void test(final Class<?> exceptionClass,
final ThreadFactory failingThreadFactory)
throws Throwable {
ThreadFactory flakyThreadFactory = new ThreadFactory() {
int seq = 0;
public Thread newThread(Runnable r) {
if (seq++ < 4)
return new Thread(r);
else
return failingThreadFactory.newThread(r);
}};
ThreadPoolExecutor pool =
new ThreadPoolExecutor(10, 10,
0L, TimeUnit.SECONDS,
new LinkedBlockingQueue(),
flakyThreadFactory);
try {
for (int i = 0; i < 8; i++)
pool.submit(new Runnable() { public void run() {} });
check(exceptionClass == null);
} catch (Throwable t) {
/* t.printStackTrace(); */
check(exceptionClass.isInstance(t));
}
pool.shutdown();
check(pool.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
}
示例12: test
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
void test(String[] args) throws Throwable {
final int threadCount = 10;
final int timeoutMillis = 30;
BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(2*threadCount);
ThreadPoolExecutor tpe
= new ThreadPoolExecutor(threadCount, threadCount,
timeoutMillis, TimeUnit.MILLISECONDS,
q, new IdentifiableThreadFactory());
equal(tpe.getCorePoolSize(), threadCount);
check(! tpe.allowsCoreThreadTimeOut());
tpe.allowCoreThreadTimeOut(true);
check(tpe.allowsCoreThreadTimeOut());
equal(countExecutorThreads(), 0);
long startTime = System.nanoTime();
for (int i = 0; i < threadCount; i++) {
tpe.submit(() -> {});
int count = countExecutorThreads();
if (millisElapsedSince(startTime) < timeoutMillis)
equal(count, i + 1);
}
while (countExecutorThreads() > 0 &&
millisElapsedSince(startTime) < LONG_DELAY_MS)
Thread.yield();
equal(countExecutorThreads(), 0);
check(millisElapsedSince(startTime) >= timeoutMillis);
tpe.shutdown();
check(tpe.allowsCoreThreadTimeOut());
check(tpe.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new Exception("Some tests failed");
}
示例13: main
import java.util.concurrent.ThreadPoolExecutor; //导入方法依赖的package包/类
/**
* @param args
*/
public static void main(String[] args) throws Exception{
/*
* Create a new Executor
*/
ThreadPoolExecutor executor=(ThreadPoolExecutor)Executors.newCachedThreadPool();
/*
* Create and submit ten tasks
*/
Random random=new Random();
for (int i=0; i<10; i++) {
Task task=new Task(random.nextInt(10000));
executor.submit(task);
}
/*
* Write information about the executor
*/
for (int i=0; i<5; i++){
showLog(executor);
TimeUnit.SECONDS.sleep(1);
}
/*
* Shutdown the executor
*/
executor.shutdown();
/*
* Write information about the executor
*/
for (int i=0; i<5; i++){
showLog(executor);
TimeUnit.SECONDS.sleep(1);
}
/*
* Wait for the finalization of the executor
*/
executor.awaitTermination(1, TimeUnit.DAYS);
/*
* Write a message to indicate the end of the program
*/
System.out.printf("Main: End of the program.\n");
}