當前位置: 首頁>>代碼示例>>Java>>正文


Java Executors.defaultThreadFactory方法代碼示例

本文整理匯總了Java中java.util.concurrent.Executors.defaultThreadFactory方法的典型用法代碼示例。如果您正苦於以下問題:Java Executors.defaultThreadFactory方法的具體用法?Java Executors.defaultThreadFactory怎麽用?Java Executors.defaultThreadFactory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.Executors的用法示例。


在下文中一共展示了Executors.defaultThreadFactory方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testShutdownDelayedTasks

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Test
public void testShutdownDelayedTasks() throws InterruptedException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());
  ex.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  ex.schedule(new Runnable() {
    public void run() {
      try {
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  }, 5000, TimeUnit.MILLISECONDS);
  ex.shutdown();
  long start = System.nanoTime();
  assertTrue(ex.awaitTermination(30, TimeUnit.SECONDS));
  long elapsed = System.nanoTime() - start;
  assertTrue("Shutdown should not have waited. Waited " + TimeUnit.NANOSECONDS.toMillis(elapsed),
      TimeUnit.SECONDS.toNanos(2) > elapsed);
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:22,代碼來源:ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java

示例2: testRepeatedExecution

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Test
public void testRepeatedExecution() throws InterruptedException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());

  final AtomicInteger counter = new AtomicInteger();
  Runnable run = new Runnable() {
    public void run() {
      counter.incrementAndGet();
    }
  };
  ScheduledFuture f = ex.scheduleAtFixedRate(run, 0, 1, TimeUnit.SECONDS);
  Awaitility.await().atMost(30, TimeUnit.SECONDS)
      .until(() -> assertEquals("Task was not executed repeatedly", true, counter.get() > 1));
  Awaitility.await().atMost(30, TimeUnit.SECONDS)
      .until(() -> assertEquals("The task could not be cancelled", true, f.cancel(true)));
  Awaitility.await().atMost(30, TimeUnit.SECONDS)
      .until(() -> assertEquals("Task was not cancelled within 30 sec", true, f.isCancelled()));
  int oldValue = counter.get();
  Thread.sleep(5000);
  assertEquals("Task was not cancelled", oldValue, counter.get());
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:23,代碼來源:ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java

示例3: getExecutor

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public XExecutor getExecutor() {
    if (executor == null) {
        synchronized (UploadThreadPool.class) {
            if (executor == null) {
                executor = new XExecutor(corePoolSize, MAX_IMUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, //
                                         new PriorityBlockingQueue<Runnable>(),   //無限容量的緩衝隊列
                                         Executors.defaultThreadFactory(),        //線程創建工廠
                                         new ThreadPoolExecutor.AbortPolicy());   //繼續超出上限的策略,阻止
            }
        }
    }
    return executor;
}
 
開發者ID:wzx54321,項目名稱:XinFramework,代碼行數:14,代碼來源:UploadThreadPool.java

示例4: create

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public ThreadPoolExecutor create() {
    // RejectedExecutionHandler 拒絕策略
    ThreadFactory threadFactory = Executors.defaultThreadFactory();
    /*
     * 參數1: 設置核心池大小
     * 參數2: 設置線程池最大能接受多少線程
     * 參數3: 當前線程數大於核心池大小、小於最大能接受線程時,超出核心池大小的線程數的生命周期
     * 參數4: 設置生命周期時間單位,秒
     * 參數5: 設置線程池緩存隊列的排隊策略為FIFO,並且指定緩存隊列大小為2
     * 參數6: 線程工廠
     */
    return new ThreadPoolExecutor(2, 5, 10, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2), threadFactory);
}
 
開發者ID:neocross,項目名稱:NeoSocket,代碼行數:15,代碼來源:Communi.java

示例5: TreadPool

import java.util.concurrent.Executors; //導入方法依賴的package包/類
private TreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
    exec = new ThreadPoolExecutor(
            corePoolSize,// 核心線程數
            maximumPoolSize,// 最大線程數
            keepAliveTime,//閑置線程存活時間
            TimeUnit.SECONDS, // 時間單位
            new LinkedBlockingDeque<Runnable>(), // 線程隊列
            Executors.defaultThreadFactory(), // 線程工廠
            new ThreadPoolExecutor.AbortPolicy() // 隊列已滿,而且當前線程數已經超過最大線程數時的異常處理策略
    );
    scheduleExec = Executors.newScheduledThreadPool(corePoolSize);
}
 
開發者ID:penghongru,項目名稱:Coder,代碼行數:13,代碼來源:UThread.java

示例6: testConcurrentExecutionAndExpiration

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Category(FlakyTest.class) // GEODE-1138: time sensitive, thread sleeps, expiration
@Test
public void testConcurrentExecutionAndExpiration()
    throws InterruptedException, ExecutionException {
  ex = new ScheduledThreadPoolExecutorWithKeepAlive(50, 1, TimeUnit.SECONDS,
      Executors.defaultThreadFactory());

  Runnable waitForABit = new Runnable() {
    public void run() {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        fail("interrupted");
      }
    }
  };

  Future[] futures = new Future[50];
  for (int i = 0; i < 50; i++) {
    futures[i] = ex.submit(waitForABit);
  }
  long start = System.nanoTime();

  for (int i = 0; i < 50; i++) {
    futures[i].get();
  }
  long end = System.nanoTime();

  assertTrue("Tasks executed in parallel", TimeUnit.NANOSECONDS.toSeconds(end - start) < 50);

  assertEquals(50, ex.getLargestPoolSize());

  // now make sure we expire back down.
  Thread.sleep(5000);
  assertEquals(1, ex.getPoolSize());
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:37,代碼來源:ScheduledThreadPoolExecutorWithKeepAliveJUnitTest.java

示例7: createPool

import java.util.concurrent.Executors; //導入方法依賴的package包/類
protected synchronized static void createPool() {
    BlockingQueue<Runnable> workers = new LinkedBlockingQueue<>();
    RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
    mDownloadPool = new DownloadPool(
            corePoolSize,
            maxPoolSize,
            keepAliveTime,
            TimeUnit.MILLISECONDS,
            workers,
            Executors.defaultThreadFactory(),
            handler);
}
 
開發者ID:Dpuntu,項目名稱:android-downloader,代碼行數:13,代碼來源:DownloadPool.java

示例8: NewRelicMeterRegistry

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public NewRelicMeterRegistry(NewRelicConfig config, Clock clock) {
    this(config, clock, Executors.defaultThreadFactory());
}
 
開發者ID:micrometer-metrics,項目名稱:micrometer,代碼行數:4,代碼來源:NewRelicMeterRegistry.java

示例9: QueuesExecutorService

import java.util.concurrent.Executors; //導入方法依賴的package包/類
protected QueuesExecutorService(int corePoolSize, int maximumPoolSize,
	Queue<Runnable> bossQueue,IndexQueueGroupManager indexQM,KeyQueueGroupManager keyQM,WaitConditionStrategy waitConditionStrategy) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),waitConditionStrategy,
    		bossQueue,indexQM,keyQM,new DirectExecutor());
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:7,代碼來源:QueuesExecutorService.java

示例10: SingleThreadTaskQueueExecutor_CountDownLatch

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public SingleThreadTaskQueueExecutor_CountDownLatch(String queueName) {
	this(queueName,Executors.defaultThreadFactory());
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:4,代碼來源:SingleThreadTaskQueueExecutor_CountDownLatch.java

示例11: DefaultQueueGroupExecutor

import java.util.concurrent.Executors; //導入方法依賴的package包/類
protected DefaultQueueGroupExecutor(int corePoolSize, int maximumPoolSize,
	Queue<Runnable> bossQueue,IndexQueueGroupManager indexQM,KeyQueueGroupManager keyQM) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE_SEC, TimeUnit.SECONDS, 
    		Executors.defaultThreadFactory(),DEFAULT_waitConditionStrategy,
    		bossQueue,indexQM,keyQM,new DirectExecutor());
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:7,代碼來源:DefaultQueueGroupExecutor.java

示例12: main

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
  if (args.length < 1) {
    System.err.println("Missing required project argument");
    System.err.printf(
        "Usage: java %s gcp-project-id [verbose]\n", SheepCounterExample.class.getName());
    return;
  }
  String project = args[0];

  // Turn up the logging verbosity
  if (args.length > 1) {
    Logger log = LogManager.getLogManager().getLogger("");
    log.setLevel(Level.ALL);
    for (Handler h : log.getHandlers()) {
      h.setLevel(Level.ALL);
    }
  }

  // Create a sample resource. In this case, a GCE Instance.
  // See https://cloud.google.com/monitoring/api/resources for a list of resource types.
  MonitoredResource monitoredResource =
      new MonitoredResource()
          .setType("gce_instance")
          .setLabels(
              ImmutableMap.of(
                  "instance_id", "test-instance",
                  "zone", "us-central1-f"));

  // Set up the Metrics infrastructure.
  MetricWriter stackdriverWriter =
      new StackdriverWriter(
          createAuthorizedMonitoringClient(),
          project,
          monitoredResource,
          STACKDRIVER_MAX_QPS,
          STACKDRIVER_MAX_POINTS_PER_REQUEST);
  final MetricReporter reporter =
      new MetricReporter(
          stackdriverWriter, METRICS_REPORTING_INTERVAL, Executors.defaultThreadFactory());
  reporter.startAsync().awaitRunning();

  // Set up a handler to stop sleeping on SIGINT.
  Runtime.getRuntime()
      .addShutdownHook(
          new Thread(
              () -> {
                reporter.stopAsync().awaitTerminated();
                // Allow the LogManager to cleanup the loggers.
                DelayedShutdownLogManager.resetFinally();
              }));

  System.err.println("Send SIGINT (Ctrl+C) to stop sleeping.");
  while (true) {
    // Count some Googley sheep.
    int colorIndex = new Random().nextInt(SHEEP_COLORS.size());
    int speciesIndex = new Random().nextInt(SHEEP_SPECIES.size());
    sheepCounter.incrementBy(1, SHEEP_COLORS.get(colorIndex), SHEEP_SPECIES.get(speciesIndex));
    sheepFluffiness.record(
        new Random().nextDouble() * 200,
        SHEEP_COLORS.get(colorIndex),
        SHEEP_SPECIES.get(speciesIndex));
    isSleeping.set(true);

    logger.info("zzz...");
    Thread.sleep(5000);
  }
}
 
開發者ID:google,項目名稱:java-monitoring-client-library,代碼行數:68,代碼來源:SheepCounterExample.java

示例13: AbstractTaskQueuesExecutor

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public AbstractTaskQueuesExecutor() {
	this(Executors.defaultThreadFactory());
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:4,代碼來源:AbstractTaskQueuesExecutor.java

示例14: ThreadPoolTaskQueuesExecutor

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public ThreadPoolTaskQueuesExecutor(int corePoolSize, int maximumPoolSize,
		WaitConditionStrategy waitConditionStrategy) {
    this(corePoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, Executors.defaultThreadFactory(),waitConditionStrategy);
}
 
開發者ID:juebanlin,項目名稱:util4j,代碼行數:5,代碼來源:ThreadPoolTaskQueuesExecutor.java

示例15: build

import java.util.concurrent.Executors; //導入方法依賴的package包/類
private static ThreadFactory build(ThreadFactoryBuilder builder) {
  final String nameFormat = builder.nameFormat;
  final Boolean daemon = builder.daemon;
  final Integer priority = builder.priority;
  final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler;
  final ThreadFactory backingThreadFactory =
      (builder.backingThreadFactory != null)
          ? builder.backingThreadFactory
          : Executors.defaultThreadFactory();
  final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null;
  return new ThreadFactory() {
    @Override
    public Thread newThread(Runnable runnable) {
      Thread thread = backingThreadFactory.newThread(runnable);
      if (nameFormat != null) {
        thread.setName(format(nameFormat, count.getAndIncrement()));
      }
      if (daemon != null) {
        thread.setDaemon(daemon);
      }
      if (priority != null) {
        thread.setPriority(priority);
      }
      if (uncaughtExceptionHandler != null) {
        thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
      }
      return thread;
    }
  };
}
 
開發者ID:zugzug90,項目名稱:guava-mock,代碼行數:31,代碼來源:ThreadFactoryBuilder.java


注:本文中的java.util.concurrent.Executors.defaultThreadFactory方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。