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


Java Executors.newFixedThreadPool方法代碼示例

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


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

示例1: main

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public static void main(String[] args) {
	ExecutorService pool = Executors.newFixedThreadPool(50);
	for(int i=0;i<50;i++){
		pool.execute(new Runnable() {
			@Override
			public void run() {
				while(true){
					Map<String, String> data = new HashMap<String, String>();
					data.put("q", "SELECT MAX(value) FROM sensor where device_code='d_bt_0' and sensor_code='s_btg_8' and time>=1485541192230000000 and time<=1485627592230000000");
					HttpRequest.post("http://10.77.110.226:8086/query?db=ruc_test1").form(data).code();
				}
			}
		});
	}
	try {
		pool.awaitTermination(Long.MAX_VALUE,TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
 
開發者ID:dbiir,項目名稱:ts-benchmark,代碼行數:21,代碼來源:HttpRequestTest.java

示例2: testMultipleClients

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Test
public void testMultipleClients() throws Exception {
  ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
  try {
    ExecutorCompletionService<Boolean> ecs =
        new ExecutorCompletionService<Boolean>(exec);
    for (int i = 0; i < NUM_THREADS; ++i)
      ecs.submit(new IdLockTestThread("client_" + i));
    for (int i = 0; i < NUM_THREADS; ++i) {
      Future<Boolean> result = ecs.take();
      assertTrue(result.get());
    }
    idLock.assertMapEmpty();
  } finally {
    exec.shutdown();
    exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
  }
}
 
開發者ID:fengchen8086,項目名稱:ditb,代碼行數:19,代碼來源:TestIdLock.java

示例3: main

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public static void main(String args[]) {
    ExecutorService executor = Executors.newFixedThreadPool(10);
    Callable<TimeZone> calTimeZone = () -> TimeZone.getDefault();
    List<Callable<TimeZone>> tasks = new ArrayList<>();
    for (int j = 1; j < 10; j++) {
        tasks.add(calTimeZone);
    }
    try {
        List<Future<TimeZone>> results = executor.invokeAll(tasks);
        for (Future<TimeZone> f : results) {
            TimeZone tz = f.get();
            if (! tz.getID().equals("GMT")) {
                throw new RuntimeException("wrong Time zone ID: " + tz.getID()
                        + ", It should be GMT");
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException("Execution interrupted or Execution Exception occurred", e);
    } finally {
        executor.shutdown();
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:Bug8066652.java

示例4: match

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public static MatchResult match(Mat scene, Mat[] templs, Method method, double scaleFactor){
		
	MatchRunner[] t = new MatchRunner[templs.length];
	ExecutorService sr = Executors.newFixedThreadPool(templs.length);
	for(int i = 0; i < templs.length; i++){
		t[i] = new MatchRunner(scene,templs[i],method,scaleFactor);
		sr.execute(t[i]);
	}
	try {
		sr.shutdown();
		sr.awaitTermination(1, TimeUnit.DAYS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	
	MatchResult best = findBestMatch(t);
	/*if(best != null){
		Imgproc.circle(scene, new Point(best.centerx +best.scaleFactor,best.centery +best.scaleFactor) ,3,new Scalar(51,51,51));
		//Imgproc.circle(scene, new Point(best.center.x ,best.center.y ) ,3,new Scalar(50,203,122));
		Imgcodecs.imwrite("/home/klein/dev/frc/test.png", scene);
	}*/
	return best;
}
 
開發者ID:Flash3388,項目名稱:FlashLib,代碼行數:24,代碼來源:CvTemplateMatcher.java

示例5: Peer

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public Peer(String host, int port) throws ConnectException {
    mConnection = Connection.fromAddress(host, port);
    if (mConnection == null) {
        throw new ConnectException("Failed to create connection");
    }

    mConnectionListener = new Connection.ConnectionListener() {
        @Override
        public void onReceived(@NonNull byte[] received) {
            handleReceiveBytes(received);
        }
    };

    mReceiveMessageService = Executors.newFixedThreadPool(1);
    mReceivedMessageBuffer = new ArrayList<>();
}
 
開發者ID:forusoul70,項目名稱:playTorrent,代碼行數:17,代碼來源:Peer.java

示例6: testOfferInExecutor

import java.util.concurrent.Executors; //導入方法依賴的package包/類
/**
 * offer transfers elements across Executor tasks
 */
public void testOfferInExecutor() {
    final LinkedBlockingDeque q = new LinkedBlockingDeque(2);
    q.add(one);
    q.add(two);
    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(three));
                threadsStarted.await();
                assertTrue(q.offer(three, LONG_DELAY_MS, MILLISECONDS));
                assertEquals(0, q.remainingCapacity());
            }});

        executor.execute(new CheckedRunnable() {
            public void realRun() throws InterruptedException {
                threadsStarted.await();
                assertSame(one, q.take());
            }});
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:26,代碼來源:LinkedBlockingDequeTest.java

示例7: main

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public static void main(String args[]) throws Exception {

        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

        fixedThreadPool.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("-----------");
        fixedThreadPool.shutdownNow();


    }
 
開發者ID:MinsxCloud,項目名稱:minsx-java-example,代碼行數:18,代碼來源:FixedThreadPool.java

示例8: activate

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Activate
public void activate(ComponentContext context) {
    alarmsExecutor = Executors.newScheduledThreadPool(CORE_POOL_SIZE);
    eventHandlingExecutor =
            Executors.newFixedThreadPool(CORE_POOL_SIZE,
                                         groupedThreads("onos/pollingalarmprovider",
                                                        "device-installer-%d", log));

    providerService = providerRegistry.register(this);

    deviceService.addListener(deviceListener);
    mastershipService.addListener(mastershipListener);

    if (context == null) {
        alarmPollFrequencySeconds = DEFAULT_POLL_FREQUENCY_SECONDS;
        log.info("No component configuration");
    } else {
        Dictionary<?, ?> properties = context.getProperties();
        alarmPollFrequencySeconds = getNewPollFrequency(properties, alarmPollFrequencySeconds);
    }
    scheduledTask = schedulePolling();
    log.info("Started");
}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:24,代碼來源:PollingAlarmProvider.java

示例9: run

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Override
public void run(String... args) {
    Client client = new Client.Builder()
            .setBaseUrl(baseUrl)
            .setClientId(clientId)
            .setClientSecret(clientSecret)
            .setUsername(username)
            .setPassword(password)
            .build();

    BlockingQueue<String> loanQueue = new LinkedBlockingQueue();
    ExecutorService service = Executors.newFixedThreadPool(4);

    LoanChangeWatcher watcher = new LoanChangeWatcher(client, loanFolder, loanQueue, service);

    LoanProcessor processor1 = new LoanProcessor(loanQueue, client, outputFile);
    LoanProcessor processor2 = new LoanProcessor(loanQueue, client, outputFile);
    LoanProcessor processor3 = new LoanProcessor(loanQueue, client, outputFile);

    service.submit(watcher);
    service.submit(processor1);
    service.submit(processor2);
    service.submit(processor3);
}
 
開發者ID:EllieMae,項目名稱:api-batchupload-sample-application,代碼行數:25,代碼來源:Main.java

示例10: MAF_Streamer

import java.util.concurrent.Executors; //導入方法依賴的package包/類
public MAF_Streamer(File queryFile, File tmpFolder, Integer chunkSize, int cores, boolean doFiltering, boolean verbose) {
	this.queryFile = queryFile;
	this.tmpFolder = tmpFolder;
	this.cores = cores;
	this.verbose = verbose;
	this.doFiltering = doFiltering;
	this.executor = Executors.newFixedThreadPool(1);
	this.chunkSize = chunkSize != null ? chunkSize : this.chunkSize;
}
 
開發者ID:BenjaminAlbrecht84,項目名稱:DAA_Converter,代碼行數:10,代碼來源:MAF_Streamer.java

示例11: parallelDrainQueue

import java.util.concurrent.Executors; //導入方法依賴的package包/類
private void parallelDrainQueue(int threadCount) {
  ExecutorService executor = Executors.newFixedThreadPool(threadCount);
  for (int i = 0; i < threadCount; i++) {
    executor.execute(new NamedRunnable("Crawler %s", i) {
      @Override protected void execute() {
        try {
          drainQueue();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
  }
  executor.shutdown();
}
 
開發者ID:dave-r12,項目名稱:okhttp-byte-counter,代碼行數:16,代碼來源:Crawler.java

示例12: runNewPool

import java.util.concurrent.Executors; //導入方法依賴的package包/類
/**
 * @param <R>
 * @param threads
 */
public static <R extends Runnable> void runNewPool(final Collection<R> threads, int max_concurrent) {
    ExecutorService pool = Executors.newFixedThreadPool(max_concurrent, factory);
    ThreadUtil.run(threads, pool, true);
}
 
開發者ID:s-store,項目名稱:s-store,代碼行數:9,代碼來源:ThreadUtil.java

示例13: testConcurrentAccessToSystemCredentials

import java.util.concurrent.Executors; //導入方法依賴的package包/類
@Test
public void testConcurrentAccessToSystemCredentials(){
  final Map<ApplicationId, ByteBuffer> testCredentials = new HashMap<>();
  ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[300]);
  ApplicationId applicationId = ApplicationId.newInstance(123456, 120);
  testCredentials.put(applicationId, byteBuffer);

  final List<Throwable> exceptions = Collections.synchronizedList(new
      ArrayList<Throwable>());

  final int NUM_THREADS = 10;
  final CountDownLatch allDone = new CountDownLatch(NUM_THREADS);
  final ExecutorService threadPool = Executors.newFixedThreadPool(
      NUM_THREADS);

  final AtomicBoolean stop = new AtomicBoolean(false);

  try {
    for (int i = 0; i < NUM_THREADS; i++) {
      threadPool.submit(new Runnable() {
        @Override
        public void run() {
          try {
            for (int i = 0; i < 100 && !stop.get(); i++) {
              NodeHeartbeatResponse nodeHeartBeatResponse =
                  newNodeHeartbeatResponse(0, NodeAction.NORMAL,
                      null, null, null, null, 0);
              nodeHeartBeatResponse.setSystemCredentialsForApps(
                  testCredentials);
              NodeHeartbeatResponseProto proto =
                  ((NodeHeartbeatResponsePBImpl)nodeHeartBeatResponse)
                      .getProto();
              Assert.assertNotNull(proto);
            }
          } catch (Throwable t) {
            exceptions.add(t);
            stop.set(true);
          } finally {
            allDone.countDown();
          }
        }
      });
    }

    int testTimeout = 2;
    Assert.assertTrue("Timeout waiting for more than " + testTimeout + " " +
            "seconds",
        allDone.await(testTimeout, TimeUnit.SECONDS));
  } catch (InterruptedException ie) {
    exceptions.add(ie);
  } finally {
    threadPool.shutdownNow();
  }
  Assert.assertTrue("Test failed with exception(s)" + exceptions,
      exceptions.isEmpty());
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:57,代碼來源:TestNodeStatusUpdater.java

示例14: execute

import java.util.concurrent.Executors; //導入方法依賴的package包/類
private void execute(Runnable runnable){
    if(mExecutorService==null){
        mExecutorService = Executors.newFixedThreadPool(3);
    }
    mExecutorService.execute(runnable);
}
 
開發者ID:natjs,項目名稱:nat-network-stream,代碼行數:7,代碼來源:DefaultHttpAdapter.java

示例15: UploadManager

import java.util.concurrent.Executors; //導入方法依賴的package包/類
private UploadManager() {
    executorService = Executors.newFixedThreadPool(10);
    idToTaskMap = new HashMap<>();
}
 
開發者ID:dhaval-mehta,項目名稱:url-to-google-drive,代碼行數:5,代碼來源:UploadManager.java


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