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


Java ThreadFactory类代码示例

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


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

示例1: openChannel

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException {
    System.err.println("* Opening socket " + isa);
    Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
    s.setKeepAlive(true);
    s.setTcpNoDelay(true);

    System.err.println("* Opening channel");
    OutputStream outputStream = s.getOutputStream();
    DataOutputStream dos = new DataOutputStream(outputStream);
    dos.writeUTF("Protocol:CLI-connect");
    ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() {

        public Thread newThread ( Runnable r ) {
            Thread t = new Thread(r, "Channel");
            t.setDaemon(true);
            return t;
        }
    });
    Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream);
    System.err.println("* Channel open");
    return c;
}
 
开发者ID:RickGray,项目名称:ysoserial-plus,代码行数:23,代码来源:JenkinsCLI.java

示例2: getExecutor

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
private static ExecutorService getExecutor() {
    synchronized (sExecutorServiceLock) {
        if (sExecutorService == null) {
            ThreadFactory threadFactory = new ThreadFactory() {
                private final AtomicInteger mCount = new AtomicInteger(1);

                    @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r,
                            "HttpUrlConnection #"
                            + mCount.getAndIncrement());
                    // Note that this thread is not doing actual networking.
                    // It's only a controller.
                    thread.setPriority(Thread.NORM_PRIORITY);
                    return thread;
                }
            };
            sExecutorService = Executors.newCachedThreadPool(threadFactory);
        }
        return sExecutorService;
    }
}
 
开发者ID:lizhangqu,项目名称:chromium-net-for-android,代码行数:23,代码来源:HttpUrlConnectionUrlRequest.java

示例3: scheduleClockUpdating

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
private void scheduleClockUpdating() {
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        }
    });
    scheduler.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            now.set(System.currentTimeMillis());
        }
    }, precision, precision, TimeUnit.MILLISECONDS);
}
 
开发者ID:y123456yz,项目名称:reading-and-annotate-rocketmq-3.4.6,代码行数:17,代码来源:SystemClock.java

示例4: afterPropertiesSet

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
@Override
public void afterPropertiesSet() throws NamingException {
	if (this.jndiName != null) {
		try {
			this.threadFactory = this.jndiLocator.lookup(this.jndiName, ThreadFactory.class);
		}
		catch (NamingException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Failed to find [java:comp/DefaultManagedThreadFactory] in JNDI", ex);
			}
			if (logger.isInfoEnabled()) {
				logger.info("Could not find default managed thread factory in JNDI - " +
						"proceeding with default local thread factory");
			}
		}
	}
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:18,代码来源:DefaultManagedAwareThreadFactory.java

示例5: createExecutor

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
private static PooledExecutorWithDMStats createExecutor(PoolStatHelper poolHelper,
    final ThreadGroup threadGroup) {
  ThreadFactory factory = new ThreadFactory() {
    private final AtomicInteger threadNum = new AtomicInteger();

    public Thread newThread(Runnable r) {
      Thread thread = new Thread(threadGroup, r,
          "locator request thread[" + threadNum.incrementAndGet() + "]");
      thread.setDaemon(true);
      return thread;
    }
  };

  return new PooledExecutorWithDMStats(new SynchronousQueue(), MAX_POOL_SIZE, poolHelper, factory,
      POOL_IDLE_TIMEOUT, new ThreadPoolExecutor.CallerRunsPolicy());
}
 
开发者ID:ampool,项目名称:monarch,代码行数:17,代码来源:TcpServer.java

示例6: customEventLoopGroup_NotClosedWhenClientIsClosed

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
@Test
public void customEventLoopGroup_NotClosedWhenClientIsClosed() throws Exception {

    ThreadFactory threadFactory = spy(new CustomThreadFactory());
    // Cannot use DefaultEventLoopGroupFactory because the concrete
    // implementation it creates is platform-dependent and could be a final
    // (i.e. non-spyable) class.
    EventLoopGroup eventLoopGroup = spy(new NioEventLoopGroup(0, threadFactory));
    EventLoopGroupConfiguration eventLoopGroupConfiguration =
            EventLoopGroupConfiguration.builder()
                                       .eventLoopGroup(eventLoopGroup)
                                       .build();
    SdkAsyncHttpClient customClient =
            NettySdkHttpClientFactory.builder()
                                     .trustAllCertificates(true)
                                     .eventLoopGroupConfiguration(eventLoopGroupConfiguration)
                                     .build()
                                     .createHttpClient();

    makeSimpleRequest(customClient);
    customClient.close();

    Mockito.verify(threadFactory, atLeastOnce()).newThread(Mockito.any());
    Mockito.verify(eventLoopGroup, never()).shutdownGracefully();
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:26,代码来源:NettyNioAsyncHttpClientWireMockTest.java

示例7: DatadogMeterRegistry

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
public DatadogMeterRegistry(DatadogConfig config, Clock clock, ThreadFactory threadFactory) {
    super(config, clock);

    this.config().namingConvention(new DatadogNamingConvention());

    try {
        this.postTimeSeriesEndpoint = URI.create(config.uri() + "/api/v1/series?api_key=" + config.apiKey()).toURL();
    } catch (MalformedURLException e) {
        // not possible
        throw new RuntimeException(e);
    }

    this.config = config;

    start(threadFactory);
}
 
开发者ID:micrometer-metrics,项目名称:micrometer,代码行数:17,代码来源:DatadogMeterRegistry.java

示例8: serviceInit

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
@Override
protected void serviceInit(Configuration conf) throws Exception {
  ThreadFactory tf = new ThreadFactoryBuilder()
    .setNameFormat("DeletionService #%d")
    .build();
  if (conf != null) {
    sched = new DelServiceSchedThreadPoolExecutor(
        conf.getInt(YarnConfiguration.NM_DELETE_THREAD_COUNT,
        YarnConfiguration.DEFAULT_NM_DELETE_THREAD_COUNT), tf);
    debugDelay = conf.getInt(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 0);
  } else {
    sched = new DelServiceSchedThreadPoolExecutor(
        YarnConfiguration.DEFAULT_NM_DELETE_THREAD_COUNT, tf);
  }
  sched.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
  sched.setKeepAliveTime(60L, SECONDS);
  if (stateStore.canRecover()) {
    recover(stateStore.loadDeletionServiceState());
  }
  super.serviceInit(conf);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:22,代码来源:DeletionService.java

示例9: QueueExecutionPool

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
/**
 * Конструктор для тестирования
 *
 * @param queueRegistry                  хранилище очередей
 * @param defaultTaskLifecycleListener   слушатель жизненного цикла задачи
 * @param defaultThreadLifecycleListener слушатель жизненного цикла потока очереди
 * @param threadFactoryProvider          фабрика фабрик создания потоков
 * @param queueThreadPoolFactory         фабрика для создания пула обработки очередей
 * @param queueLoopFactory               фабрика для создания {@link QueueLoop}
 * @param queueRunnerFactory             фабрика для создания {@link QueueRunner}
 */
QueueExecutionPool(@Nonnull QueueRegistry queueRegistry,
                   @Nonnull TaskLifecycleListener defaultTaskLifecycleListener,
                   @Nonnull ThreadLifecycleListener defaultThreadLifecycleListener,
                   @Nonnull BiFunction<QueueLocation, QueueShardId, ThreadFactory> threadFactoryProvider,
                   @Nonnull BiFunction<Integer, ThreadFactory, ExecutorService> queueThreadPoolFactory,
                   @Nonnull Function<ThreadLifecycleListener, QueueLoop> queueLoopFactory,
                   @Nonnull Function<ShardPoolInstance, QueueRunner> queueRunnerFactory) {
    this.queueRegistry = Objects.requireNonNull(queueRegistry);
    this.defaultTaskLifecycleListener = Objects.requireNonNull(defaultTaskLifecycleListener);
    this.defaultThreadLifecycleListener = Objects.requireNonNull(defaultThreadLifecycleListener);
    this.queueThreadPoolFactory = Objects.requireNonNull(queueThreadPoolFactory);
    this.threadFactoryProvider = Objects.requireNonNull(threadFactoryProvider);
    this.queueLoopFactory = Objects.requireNonNull(queueLoopFactory);
    this.queueRunnerFactory = Objects.requireNonNull(queueRunnerFactory);
}
 
开发者ID:yandex-money,项目名称:db-queue,代码行数:27,代码来源:QueueExecutionPool.java

示例10: ServiceCacheImplProxy

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
public ServiceCacheImplProxy(ServiceDiscoveryImpl<T> discovery, String name, ThreadFactory threadFactory) {
    this.serviceCacheImpl = new ServiceCacheImpl<T>(discovery, name, threadFactory);

    try {
        Field privateListenerContainerField = ServiceCacheImpl.class.getDeclaredField("listenerContainer");
        privateListenerContainerField.setAccessible(true);
        this.listenerContainer = (ListenerContainer)privateListenerContainerField.get(serviceCacheImpl);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        log.error("Failed to construct Service Cache. Container listeners is null.");
    }

    Preconditions.checkNotNull(discovery, "discovery cannot be null");
    Preconditions.checkNotNull(name, "name cannot be null");
    Preconditions.checkNotNull(threadFactory, "threadFactory cannot be null");
    Preconditions.checkNotNull(this.listenerContainer, "container of listeners can not be null");


    this.discovery = discovery;
    this.cache = new PathChildrenCache(discovery.getClient(), discovery.pathForName(name), true, threadFactory);
    this.cache.getListenable().addListener(this);
}
 
开发者ID:Comcast,项目名称:redirector,代码行数:22,代码来源:ServiceCacheImplProxy.java

示例11: ServerListener

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
/**
 * Create a new server listener.
 * @param serverConnector connector
 * @param socketFactory socket factory
 * @param authenticator authenticator
 * @param accessController access controller
 * @param threadPriority  thread priority
 * @throws IOException if an I/O error occurs when constructing the server listener
 */
ServerListener(final ServerConnector serverConnector, final JMXSocketFactory socketFactory, final JMXAuthenticator authenticator,
               final JMXAccessController accessController, final int threadPriority) throws IOException {
    this.serverConnector = serverConnector;
    this.authenticator = authenticator;
    this.accessController = accessController;
    serverId = SERVER_ID.getAndIncrement();

    // Setup executor service
    final ThreadFactory threadFactory = new ConnectionThreadFactory(serverId, threadPriority);
    executorService = Executors.newCachedThreadPool(threadFactory);

    // Setup server socket
    serverSocket = socketFactory.createServerSocket(serverConnector.getAddress());
    serverConnector.updateAddress(serverSocket.getLocalPort());
    serverSocket.setSoTimeout(0);
}
 
开发者ID:MinBZK,项目名称:OperatieBRP,代码行数:26,代码来源:ServerListener.java

示例12: getDefaultCommitExecutor

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
/**
 * @deprecated This method is only used from configuration modules and thus callers of it
 *             should use service injection to make the executor configurable.
 */
@Deprecated
public static synchronized ListeningExecutorService getDefaultCommitExecutor() {
    if (COMMIT_EXECUTOR == null) {
        final ThreadFactory factory = new ThreadFactoryBuilder().setDaemon(true).setNameFormat("md-sal-binding-commit-%d").build();
        /*
         * FIXME: this used to be newCacheThreadPool(), but MD-SAL does not have transaction
         *        ordering guarantees, which means that using a concurrent threadpool results
         *        in application data being committed in random order, potentially resulting
         *        in inconsistent data being present. Once proper primitives are introduced,
         *        concurrency can be reintroduced.
         */
        final ExecutorService executor = Executors.newSingleThreadExecutor(factory);
        COMMIT_EXECUTOR = MoreExecutors.listeningDecorator(executor);
    }

    return COMMIT_EXECUTOR;
}
 
开发者ID:hashsdn,项目名称:hashsdn-controller,代码行数:22,代码来源:SingletonHolder.java

示例13: CustomTPE

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
CustomTPE(int corePoolSize,
          int maximumPoolSize,
          long keepAliveTime,
          TimeUnit unit,
          BlockingQueue<Runnable> workQueue,
          ThreadFactory threadFactory,
          RejectedExecutionHandler handler) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit,
      workQueue, threadFactory, handler);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:11,代码来源:ThreadPoolExecutorSubclassTest.java

示例14: DebuggableThreadPoolExecutor

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
public DebuggableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory)
{
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    allowCoreThreadTimeOut(true);

    // block task submissions until queue has room.
    // this is fighting TPE's design a bit because TPE rejects if queue.offer reports a full queue.
    // we'll just override this with a handler that retries until it gets in.  ugly, but effective.
    // (there is an extensive analysis of the options here at
    //  http://today.java.net/pub/a/today/2008/10/23/creating-a-notifying-blocking-thread-pool-executor.html)
    this.setRejectedExecutionHandler(blockingExecutionHandler);
}
 
开发者ID:Netflix,项目名称:sstable-adaptor,代码行数:13,代码来源:DebuggableThreadPoolExecutor.java

示例15: getThreadFactory

import java.util.concurrent.ThreadFactory; //导入依赖的package包/类
private static ThreadFactory getThreadFactory(final String name) {
    return new ThreadFactory() {
        private int threadCount = 1;

        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            if (name != null) {
                thread.setName(name + "-" + threadCount++);
            }
            thread.setPriority(Thread.MAX_PRIORITY);
            return thread;
        }
    };
}
 
开发者ID:aws,项目名称:aws-sdk-java-v2,代码行数:15,代码来源:TimeoutThreadPoolBuilder.java


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