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


Java Executors类代码示例

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


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

示例1: testBug75615

import java.util.concurrent.Executors; //导入依赖的package包/类
public void testBug75615() throws Exception {
    // Main use case: although this could cause an exception due to a race condition in MysqlIO.mysqlConnection it is silently swallowed within the running
    // thread.
    final Connection testConn1 = getConnectionWithProps("");
    testConn1.setNetworkTimeout(Executors.newSingleThreadExecutor(), 1000);
    testConn1.close();

    // Main use case simulation: this simulates the above by capturing an eventual exeption in the main thread. This is where this test would actually fail.
    // This part is repeated several times to increase the chance of hitting the reported bug.
    for (int i = 0; i < 25; i++) {
        final ExecutorService execService = Executors.newSingleThreadExecutor();
        final Connection testConn2 = getConnectionWithProps("");
        testConn2.setNetworkTimeout(new Executor() {
            public void execute(Runnable command) {
                // Attach the future to the parent object so that it can track the exception in the main thread.
                ConnectionRegressionTest.this.testBug75615Future = execService.submit(command);
            }
        }, 1000);
        testConn2.close();
        try {
            this.testBug75615Future.get();
        } catch (ExecutionException e) {
            e.getCause().printStackTrace();
            fail("Exception thrown in the thread that was setting the network timeout: " + e.getCause());
        }
        execService.shutdownNow();
    }

    // Test the expected exception on null executor.
    assertThrows(SQLException.class, "Executor can not be null", new Callable<Void>() {
        public Void call() throws Exception {
            Connection testConn = getConnectionWithProps("");
            testConn.setNetworkTimeout(null, 1000);
            testConn.close();
            return null;
        }
    });
}
 
开发者ID:bragex,项目名称:the-vigilantes,代码行数:39,代码来源:ConnectionRegressionTest.java

示例2: setUp

import java.util.concurrent.Executors; //导入依赖的package包/类
@Override protected void setUp() {
  final ExecutorService executor = Executors.newSingleThreadExecutor();
  tearDownStack.addTearDown(new TearDown() {
    @Override
    public void tearDown() {
      executor.shutdownNow();
    }
  });
  sleeper = new SleepingRunnable(1000);
  delayedFuture = executor.submit(sleeper, true);

  tearDownStack.addTearDown(new TearDown() {
    @Override
    public void tearDown() {
      Thread.interrupted();
    }
  });
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:19,代码来源:UninterruptibleFutureTest.java

示例3: newThread

import java.util.concurrent.Executors; //导入依赖的package包/类
@Override
public Thread newThread(final Runnable r) {
    return Executors.defaultThreadFactory().newThread(new Runnable() {
        @Override
        public void run() {
            Thread.currentThread().setName("JavaCronetEngine");
            // On android, all background threads (and all threads that are part
            // of background processes) are put in a cgroup that is allowed to
            // consume up to 5% of CPU - these worker threads spend the vast
            // majority of their time waiting on I/O, so making them contend with
            // background applications for a slice of CPU doesn't make much sense.
            // We want to hurry up and get idle.
            android.os.Process.setThreadPriority(
                    THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);
            r.run();
        }
    });
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:19,代码来源:JavaCronetEngine.java

示例4: testSValue

import java.util.concurrent.Executors; //导入依赖的package包/类
@Test
public void testSValue() throws Exception {
    // Check that we never generate an S value that is larger than half the curve order. This avoids a malleability
    // issue that can allow someone to change a transaction [hash] without invalidating the signature.
    final int ITERATIONS = 10;
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(ITERATIONS));
    List<ListenableFuture<ECKey.ECDSASignature>> sigFutures = Lists.newArrayList();
    final ECKey key = new ECKey();
    for (byte i = 0; i < ITERATIONS; i++) {
        final byte[] hash = HashUtil.sha3(new byte[]{i});
        sigFutures.add(executor.submit(new Callable<ECDSASignature>() {
            @Override
            public ECKey.ECDSASignature call() throws Exception {
                return key.doSign(hash);
            }
        }));
    }
    List<ECKey.ECDSASignature> sigs = Futures.allAsList(sigFutures).get();
    for (ECKey.ECDSASignature signature : sigs) {
        assertTrue(signature.s.compareTo(ECKey.HALF_CURVE_ORDER) <= 0);
    }
    final ECKey.ECDSASignature duplicate = new ECKey.ECDSASignature(sigs.get(0).r, sigs.get(0).s);
    assertEquals(sigs.get(0), duplicate);
    assertEquals(sigs.get(0).hashCode(), duplicate.hashCode());
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:26,代码来源:ECKeyTest.java

示例5: main

import java.util.concurrent.Executors; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException
{
   // create new thread pool with two threads
   ExecutorService executorService = Executors.newCachedThreadPool();

   // create SynchronizedBuffer to store ints
   Buffer sharedLocation = new SynchronizedBuffer();

   System.out.printf("%-40s%s\t\t%s%n%-40s%s%n%n", "Operation", 
      "Buffer", "Occupied", "---------", "------\t\t--------");

   // execute the Producer and Consumer tasks
   executorService.execute(new Producer(sharedLocation));
   executorService.execute(new Consumer(sharedLocation));

   executorService.shutdown();
   executorService.awaitTermination(1, TimeUnit.MINUTES); 
}
 
开发者ID:cleitonferreira,项目名称:LivroJavaComoProgramar10Edicao,代码行数:19,代码来源:SharedBufferTest2.java

示例6: testSubmitPrivilegedExceptionAction

import java.util.concurrent.Executors; //导入依赖的package包/类
/**
 * A submitted privileged exception action runs to completion
 */
public void testSubmitPrivilegedExceptionAction() throws Exception {
    final Callable callable =
        Executors.callable(new PrivilegedExceptionAction() {
            public Object run() { return TEST_STRING; }});
    Runnable r = new CheckedRunnable() {
    public void realRun() throws Exception {
        ExecutorService e = new ForkJoinPool(1);
        try (PoolCleaner cleaner = cleaner(e)) {
            Future future = e.submit(callable);
            assertSame(TEST_STRING, future.get());
        }
    }};

    runWithPermissions(r, new RuntimePermission("modifyThread"));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:ForkJoinPoolTest.java

示例7: schedule

import java.util.concurrent.Executors; //导入依赖的package包/类
/**
 * 定时清数据
 */
private void schedule() {
    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("recoder"));
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            try {
                CallbackRecoder.recordTime();
                CallbackRecoder.calCallbackCount();
                RequestRecoder.calProviderRegistryCount();
                RequestRecoder.calConsumerRegistryCount();
                IpRequestHandler.calAllCount();
                sendMonitorData();
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    }, getDelaySecond(), interval, TimeUnit.SECONDS);
}
 
开发者ID:tiglabs,项目名称:jsf-core,代码行数:21,代码来源:RecorderSchedule.java

示例8: reentrantlock

import java.util.concurrent.Executors; //导入依赖的package包/类
private void reentrantlock() {

        ExecutorService executor = Executors.newFixedThreadPool(2);
        ReentrantLock lock = new ReentrantLock();

        executor.submit(() -> {
            lock.lock();
            try {
                sleep(1);
            } finally {
                lock.unlock();
            }
        });

        executor.submit(() -> {
            System.out.println("Locked: " + lock.isLocked());
            System.out.println("Held by me: " + lock.isHeldByCurrentThread());
            boolean locked = lock.tryLock();
            System.out.println("Lock acquired: " + locked);
        });

        stop(executor);
    }
 
开发者ID:daishicheng,项目名称:outcomes,代码行数:24,代码来源:Main.java

示例9: init

import java.util.concurrent.Executors; //导入依赖的package包/类
@Override
public void init() {
    if (config.listenPort() > 0) {
        peerServiceExecutor = Executors.newSingleThreadExecutor(runnable -> {
            Thread thread = new Thread(runnable, "Peer Server");
            thread.setUncaughtExceptionHandler((exceptionThread, exception) -> {
                gLogger.error("Unable to start peer server", exception);
            });
            return thread;
        });
        peerServiceExecutor.execute(() -> peerServer.start(config.listenPort()));
    }
    compositeEthereumListener.addListener(gasPriceTracker);

    gLogger.info("RskJ node started: enode://{}@{}:{}" , Hex.toHexString(config.nodeId()), config.getExternalIp(), config.listenPort());
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:17,代码来源:EthereumImpl.java

示例10: multiThreadedSavePdfTablePageDebugImage

import java.util.concurrent.Executors; //导入依赖的package包/类
@Test
public void multiThreadedSavePdfTablePageDebugImage() throws IOException {
    long start = System.currentTimeMillis();
    PdfTableReader reader = new PdfTableReader();
    ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

    List<Future<Boolean>> futures = new ArrayList<>();
    for (final int pageNum : IntStream.rangeClosed(1, PDFdoc.getNumberOfPages()).toArray()) {
        Callable<Boolean> callable = () -> {
            reader.savePdfTablePageDebugImage(PDFdoc, pageNum, TEST_OUT_PATH);
            return true;
        };
        futures.add(executor.submit(callable));
    }

    try {
        for (Future<Boolean> f : futures) {
            f.get();
        }
    } catch (Exception e) {
        throw new TestException(e);
    }

    long end = System.currentTimeMillis();
    System.out.println("save debug images - multi thread: " + (end - start) / 1000.0);
}
 
开发者ID:rostrovsky,项目名称:pdf-table,代码行数:27,代码来源:PdfTableReaderTest.java

示例11: initDisruptor

import java.util.concurrent.Executors; //导入依赖的package包/类
private void initDisruptor(int processors, int ringBufferSize) {
  LOG.info("eds client init disruptor with processors="
      + processors + " and ringBufferSize=" + ringBufferSize);

  executor = Executors.newFixedThreadPool(
      processors,
      new ThreadFactoryBuilder().setNameFormat("disruptor-executor-%d").build());

  final WaitStrategy waitStrategy = createWaitStrategy();
  ringBufferSize = sizeFor(ringBufferSize); // power of 2
  disruptor = new Disruptor<>(EdsRingBufferEvent.FACTORY, ringBufferSize, executor,
      ProducerType.MULTI, waitStrategy);

  EdsEventWorkHandler[] handlers = new EdsEventWorkHandler[processors];
  for (int i = 0; i < handlers.length; i++) {
    handlers[i] = new EdsEventWorkHandler();
  }
  // handlers number = threads number
  disruptor.handleEventsWithWorkerPool(handlers); // "handleEventsWith" just like topics , with multiple consumers

  disruptor.start();
}
 
开发者ID:eXcellme,项目名称:eds,代码行数:23,代码来源:PublishManager.java

示例12: RemotingNettyClient

import java.util.concurrent.Executors; //导入依赖的package包/类
private RemotingNettyClient(final NettyClientConfig nettyClientConfig) {
    super(nettyClientConfig.getOnewaySemaphoreValue(), nettyClientConfig.getAsyncSemaphoreValue());
    int publicThreadNums = nettyClientConfig.getCallbackExecutorThreads();
    if (publicThreadNums <= 0) {
        publicThreadNums = 4;
    }
    this.publicExecutor = Executors.newFixedThreadPool(publicThreadNums, new ThreadFactory() {
        private AtomicInteger threadIndex = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyClientPublicExecutor_" + this.threadIndex.incrementAndGet());
        }
    });

    group = new NioEventLoopGroup(nettyClientConfig.getWorkerThreads(), new CustomThreadFactory("client"));

    start();
}
 
开发者ID:lemonJun,项目名称:TakinRPC,代码行数:20,代码来源:RemotingNettyClient.java

示例13: setup

import java.util.concurrent.Executors; //导入依赖的package包/类
@Setup
public void setup() {
	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
	executor.schedule(
			() -> {
				System.out.println("Deoptimize: 1");
				state = 1;
			},
			25, TimeUnit.SECONDS);
	executor.schedule(
			() -> {
				System.out.println("Deoptimize :0");
				state = 0;
			},
			30, TimeUnit.SECONDS);
}
 
开发者ID:dodie,项目名称:jvm-dynamic-optimizations-performance-test,代码行数:17,代码来源:Nullness.java

示例14: init

import java.util.concurrent.Executors; //导入依赖的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

示例15: whileOutLog

import java.util.concurrent.Executors; //导入依赖的package包/类
private void whileOutLog(String outs) {

        ser = Executors.newSingleThreadExecutor();
        ser.execute(new Runnable() {

            @Override
            public void run() {

                while (true) {
                    try {
                        logger.info("Test HBase insert Log info-" + new Date());
                        Thread.sleep(5000);
                    }
                    catch (InterruptedException e) {
                    }
                }

            }
        });
    }
 
开发者ID:uavorg,项目名称:uavstack,代码行数:21,代码来源:Log4jTest.java


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