本文整理汇总了Java中java.util.concurrent.ExecutorService.execute方法的典型用法代码示例。如果您正苦于以下问题:Java ExecutorService.execute方法的具体用法?Java ExecutorService.execute怎么用?Java ExecutorService.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.ExecutorService
的用法示例。
在下文中一共展示了ExecutorService.execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testOfferInExecutor
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public void testOfferInExecutor(boolean fair) {
final SynchronousQueue q = new SynchronousQueue(fair);
final CheckedBarrier threadsStarted = new CheckedBarrier(2);
final ExecutorService executor = Executors.newFixedThreadPool(2);
try (PoolCleaner cleaner = cleaner(executor)) {
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
assertFalse(q.offer(one));
threadsStarted.await();
assertTrue(q.offer(one, LONG_DELAY_MS, MILLISECONDS));
assertEquals(0, q.remainingCapacity());
}});
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
threadsStarted.await();
assertSame(one, q.take());
}});
}
}
示例2: testPollInExecutor
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* timed poll retrieves elements across Executor threads
*/
public void testPollInExecutor() {
final LinkedTransferQueue q = new LinkedTransferQueue();
final CheckedBarrier threadsStarted = new CheckedBarrier(2);
final ExecutorService executor = Executors.newFixedThreadPool(2);
try (PoolCleaner cleaner = cleaner(executor)) {
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
assertNull(q.poll());
threadsStarted.await();
long startTime = System.nanoTime();
assertSame(one, q.poll(LONG_DELAY_MS, MILLISECONDS));
assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
checkEmpty(q);
}});
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
threadsStarted.await();
q.put(one);
}});
}
}
示例3: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) {
//创建并发访问的账户
MyCount myCount = new MyCount("95599200901215522", 10000);
//创建一个锁对象
ReadWriteLock lock = new ReentrantReadWriteLock(false);
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
//创建一些并发访问用户,一个信用卡,存的存,取的取,好热闹啊
User u1 = new User("张三", myCount, -4000, lock, true);
User u2 = new User("张三他爹", myCount, 6000, lock, false);
User u3 = new User("张三他弟", myCount, -8000, lock, false);
User u4 = new User("张三", myCount, 800, lock, false);
User u5 = new User("张三他爹", myCount, 0, lock, true);
//在线程池中执行各个用户的操作
pool.execute(u1);
pool.execute(u2);
pool.execute(u3);
pool.execute(u4);
pool.execute(u5);
//关闭线程池
pool.shutdown();
}
示例4: startClient
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public void startClient()
{
try // connect to server and get streams
{
// make connection to server
connection = new Socket(
InetAddress.getByName(ticTacToeHost), 12345);
// get streams for input and output
input = new Scanner(connection.getInputStream());
output = new Formatter(connection.getOutputStream());
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
// create and start worker thread for this client
ExecutorService worker = Executors.newFixedThreadPool(1);
worker.execute(this); // execute client
}
示例5: generateMaxSet
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
private void generateMaxSet() throws AlgorithmExecutionException {
if (this.optimize()) {
this.maxSet = new CopyOnWriteArrayList<MAX_SET>();
ExecutorService exec = this.getExecuter();
for (int i = 0; i < this.numberOfAttributes; ++i) {
exec.execute(new RunnerThreadMaxSet(i));
}
this.awaitExecuter(exec);
} else {
this.maxSet = new LinkedList<MAX_SET>();
for (int i = 0; i < this.numberOfAttributes; ++i) {
executeMax_Set_Task(i);
}
}
}
示例6: testPollInExecutor
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* timed poll transfers elements across Executor tasks
*/
public void testPollInExecutor() {
final DelayQueue q = new DelayQueue();
final CheckedBarrier threadsStarted = new CheckedBarrier(2);
final ExecutorService executor = Executors.newFixedThreadPool(2);
try (PoolCleaner cleaner = cleaner(executor)) {
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
assertNull(q.poll());
threadsStarted.await();
assertNotNull(q.poll(LONG_DELAY_MS, MILLISECONDS));
checkEmpty(q);
}});
executor.execute(new CheckedRunnable() {
public void realRun() throws InterruptedException {
threadsStarted.await();
q.put(new PDelay(1));
}});
}
}
示例7: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) throws Throwable {
final int nThreads = 16;
final int writes = 1000;
final File file = File.createTempFile("foo", null);
try {
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
for (int i = 0; i < nThreads; i++)
pool.execute(new Runnable() { public void run() {
try {
// randomly choose FileChannel or OutputStream
if (rand.nextBoolean()) {
try (FileChannel fc = newFileChannel(file)) {
for (int j=0; j<writes; j++) write(fc, 'x');
}
} else {
try (OutputStream out = newOutputStream(file)) {
for (int j = 0; j<writes; j++) out.write('x');
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}});
pool.shutdown();
pool.awaitTermination(1L, TimeUnit.MINUTES);
if (file.length() != (long) (nThreads * writes))
throw new RuntimeException("File not expected length");
} finally {
file.delete();
}
}
示例8: getPage
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/** 根据Id查询(cls返回类型Class) */
public <K> Page<K> getPage(final Page<Long> ids, final Class<K> cls) {
if (ids != null) {
Page<K> page = new Page<K>(ids.getCurrent(), ids.getSize());
page.setTotal(ids.getTotal());
final List<K> records = InstanceUtil.newArrayList();
for (int i = 0; i < ids.getRecords().size(); i++) {
records.add(null);
}
int thread = Math.min(maxThread, Math.max(1, records.size() / 2));
ExecutorService executorService = Executors.newFixedThreadPool(thread);
for (int i = 0; i < ids.getRecords().size(); i++) {
final int index = i;
executorService.execute(new Runnable() {
public void run() {
T t = queryById(ids.getRecords().get(index));
K k = InstanceUtil.to(t, cls);
records.set(index, k);
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
} catch (InterruptedException e) {
logger.error("awaitTermination", "", e);
}
page.setRecords(records);
return page;
}
return new Page<K>();
}
示例9: scanportsetfun
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public void scanportsetfun() {
int threadNum;
threadNum=Integer.parseInt(TheardNum.getText().trim());
String[] portsString = textportlist.getText().split(",");
int[] ports = new int[portsString.length];
for(int ii=0;ii<portsString.length;ii++)
ports[ii] = Integer.parseInt(portsString[ii].trim());
Result.append("scanning"+" "+Lsaportscan.hostaddress+"'s port set!"+"\n");
ExecutorService threadPool = Executors.newCachedThreadPool();
for (int i = 0; i < threadNum; i++) {
Portset portset = new Portset(ports,threadNum,i);
threadPool.execute(portset);
}
threadPool.shutdown();
while (true) {
if (threadPool.isTerminated()) {
//System.out.println("OVER!!!!!!!!!!!!!!!");
Result.append("-------------------------Over!!!----------------------\n\n");
stateResult.setText("OVER !");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
}
}
示例10: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public static void main(String[] args) throws Exception {
String passPath = "password.txt";
String dictPath = "dictionary.txt";
System.out.println("Loading dictionary");
List<String> dictionary = new ArrayList<String>();
// store dictionary file in memory
try (BufferedReader reader = new BufferedReader(new FileReader(dictPath))) {
String line;
while ((line = reader.readLine()) != null) {
dictionary.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Dictionary loaded");
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// queue of items (containing a word and it's hash equivalent) added to by producers, taken by consumer
BlockingQueue<Item> queue = new LinkedBlockingQueue<Item>();
// checks given hashed word from producers against hashes stored in password text file
// single consumer serialises writes, avoids concurrent mangling of output file
Runnable consumer = new Consumer(queue, passPath);
executor.execute(consumer);
System.out.println("Consumer started");
// each thread has increasing approximate computation time based on i
for (int i = 1; i <= 20; i++) {
// hashes words from those stored in dictionary text file, sends to consumer to check
Runnable producer = new Producer(queue, dictionary, i);
executor.execute(producer);
System.out.println("Producer " + i + " started");
}
}
示例11: testDubboMultiThreadInvoke
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
public void testDubboMultiThreadInvoke() throws Exception
{
Exporter<?> rpcExporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.class, URL.valueOf("dubbo://127.0.0.1:20259/TestService")));
final AtomicInteger counter = new AtomicInteger();
final DemoService service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:20259/TestService")));
assertEquals(service.getSize(new String[]{"123", "456", "789"}), 3);
final StringBuffer sb = new StringBuffer();
for(int i=0;i<1024*64+32;i++)
sb.append('A');
assertEquals(sb.toString(), service.echo(sb.toString()));
ExecutorService exec = Executors.newFixedThreadPool(10);
for(int i=0;i<10;i++)
{
final int fi = i;
exec.execute(new Runnable(){
public void run()
{
for(int i=0;i<30;i++)
{
System.out.println(fi+":"+counter.getAndIncrement());
assertEquals(service.echo(sb.toString()), sb.toString());
}
}
});
}
exec.shutdown();
exec.awaitTermination(10, TimeUnit.SECONDS);
rpcExporter.unexport();
}
示例12: testMultiInstanceConcurrencySequentiallyLaunched
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
protected void testMultiInstanceConcurrencySequentiallyLaunched(int iterations, final RedissonRunnable runnable) throws InterruptedException {
System.out.println("Multi Instance Concurrent Job Interation: " + iterations);
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
final Map<Integer, RedissonClient> instances = new HashMap<Integer, RedissonClient>();
for (int i = 0; i < iterations; i++) {
instances.put(i, BaseTest.createInstance());
}
long watch = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
final int n = i;
executor.execute(() -> runnable.run(instances.get(n)));
}
executor.shutdown();
Assert.assertTrue(executor.awaitTermination(5, TimeUnit.MINUTES));
System.out.println("multi: " + (System.currentTimeMillis() - watch));
executor = Executors.newCachedThreadPool();
for (final RedissonClient redisson : instances.values()) {
executor.execute(() -> redisson.shutdown());
}
executor.shutdown();
Assert.assertTrue(executor.awaitTermination(5, TimeUnit.MINUTES));
}
示例13: go
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* 启动多线程查询
*/
public void go() {
ExecutorService executorService = Executors.newFixedThreadPool(Integer.parseInt(Constant.THREAD_POOL_SIZE));
for (int i = 0; i < Integer.parseInt(Constant.THREAD_NUM); ++i) {
log.info("thread " + i + " is ready start!");
executorService.execute(new Task());
log.info("thread " + i + " has finished!");
}
executorService.shutdown();
}
示例14: main
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* @param args
*/
public static void main(String[] args) {
final List<Integer> list = new ArrayList<Integer>(52);
ExecutorService service = Executors.newFixedThreadPool(50);
int i = 0;
while (i++ < 50) {
service.execute(new Runnable() {
@Override
public void run() {
// while (true) {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
Random r = new Random();
list.add(r.nextInt(30));
// }
}
});
}
while(true) {
System.out.println(list.size());
}
}
示例15: run
import java.util.concurrent.ExecutorService; //导入方法依赖的package包/类
/**
* Runs the command.
*
* @param command the list of command line tokens
* @return the output of the command as a list of lines
* @throws GradleException if the command exited with non-zero exit code
*/
public List<String> run(List<String> command) throws IOException, InterruptedException {
if (logger != null) {
logger.debug("Running command : " + String.join(" ", command));
}
ExecutorService executor = executorServiceFactory.createExecutorService();
// Builds the command to execute.
ProcessBuilder processBuilder = processBuilderFactory.createProcessBuilder();
processBuilder.command(command);
processBuilder.redirectErrorStream(true);
if (environment != null) {
processBuilder.environment().putAll(environment);
}
final Process process = processBuilder.start();
// Runs the command and streams the output.
List<String> output = new ArrayList<>();
executor.execute(outputConsumerRunnable(process, output));
int exitCode = process.waitFor();
// Shuts down the executor.
executor.shutdown();
try {
executor.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
if (logger != null) {
logger.debug("Task Executor interrupted waiting for output consumer thread");
}
}
// Stops the build if the command fails to do something, we may want to make this configurable.
if (exitCode != 0) {
throw new GradleException("command exited with non-zero exit code : " + exitCode);
}
return output;
}