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


Java TimeUnit类代码示例

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


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

示例1: getInstance

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
public static synchronized OKHttpUtil getInstance(){
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
                        CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build();
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
//                .connectionSpecs(Collections.singletonList(spec)).
                .addInterceptor(new RetryInterceptor())
                .build();
        return INSTANCE;
    }
 
开发者ID:huang-kai,项目名称:auto-scale-java,代码行数:18,代码来源:OKHttpUtil.java

示例2: testMultipleClients

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

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
@Test
	public void mdc_context_should_be_propagated() throws InterruptedException, ExecutionException {
//		ExecutorService executorService = Executors.newFixedThreadPool(4);
		ExecutorService executorService = new ThreadPoolTaskExecutorWithMdcPropagation(4, 4, 50, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
		List<Future<String>> futures = new ArrayList<Future<String>>();
		List<String> expectedTasks = new ArrayList<>();
		for(int i=0; i<100; i++) {
			MDC.put("requestId", "task"+i);
			expectedTasks.add("task"+i);
			futures.add(executorService.submit(new Callable<String>() {
				@Override
				public String call() throws Exception {
					Thread.sleep(100);
					return MDC.get("requestId");
				}
			}));
		}
		
		for(Future<String> f : futures) {
			String t = f.get();
			if(!expectedTasks.remove(t)) {
				Assert.fail("Unexpected task: "+t);
			}
		}
		if(!expectedTasks.isEmpty()) {
			Assert.fail("Expected tasks not returned: "+expectedTasks);
		}
	}
 
开发者ID:Orange-OpenSource,项目名称:orange-mathoms-logging,代码行数:29,代码来源:ThreadPoolTaskExecutorWithMdcPropagationTest.java

示例4: testValueParserFailingOnReload

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
@Test
public void testValueParserFailingOnReload() throws Exception {
  when(configSource.loadConfig())
      .thenReturn(toConfigProps(mapBuilder().put("int", "1").build()))
      .thenReturn(toConfigProps(mapBuilder().put("int", "not an int").build()));
  ConfigRegistryImpl configRegistry = newConfigRegistry(configSource);

  IntConfigProperty intProperty = configRegistry.intProperty("int");
  intProperty.addValidator(Objects::nonNull);
  intProperty.addValidator(i -> i >= 1);
  intProperty.addCallback((i1, i2) -> sideEffect.apply(i1, i2));

  assertTrue(intProperty.value().isPresent());
  assertEquals(1, (int) intProperty.value().get());

  TimeUnit.MILLISECONDS.sleep(WAIT_FOR_RELOAD_PERIOD_MILLIS);

  assertTrue(intProperty.value().isPresent());
  assertEquals(1, (int) intProperty.value().get());
  verify(sideEffect, never()).apply(any(), any());
}
 
开发者ID:scalecube,项目名称:config,代码行数:22,代码来源:SimpleConfigPropertyTest.java

示例5: addInvalidNonce

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
private boolean addInvalidNonce(final Nonce nonce, final XnioExecutor executor) {
    long now = System.currentTimeMillis();
    long invalidBefore = now - firstUseTimeOut;

    long timeTillInvalid = nonce.timeStamp - invalidBefore;
    if (timeTillInvalid > 0) {
        if (invalidNonces.add(nonce.nonce)) {
            executor.executeAfter(new InvalidNonceCleaner(nonce.nonce), timeTillInvalid, TimeUnit.MILLISECONDS);
            return true;
        } else {
            return false;
        }
    } else {
        // So close to expiring any record of this nonce being used could have been cleared so
        // don't take a chance and just say no.
        return false;
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:19,代码来源:SimpleNonceManager.java

示例6: create

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
public static   <T> T create(Class<T> c, String url) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)//日志拦截器
            .addNetworkInterceptor(new CommonInterceptor())//网络拦截器,进行重定向等操作
            .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时
            .build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(XJsonConverterFactory.create())//json数据转换
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//将Callable接口转换成Observable接口
            .client(client)//网络请求客户端为okhttp
            .build();
    return retrofit.create(c);
}
 
开发者ID:killnono,项目名称:Dalaran,代码行数:17,代码来源:XApiServiceHelper.java

示例7: waitUntilCompleted

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
protected void waitUntilCompleted() {
    while (!completed.get()) {
        try {
            if (duration > 0) {
                TimeUnit unit = getTimeUnit();
                LOG.info("Waiting for: " + duration + " " + unit);
                latch.await(duration, unit);
                exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, durationHitExitCode);
                completed.set(true);
            } else {
                latch.await();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
 
开发者ID:drinkwater-io,项目名称:drinkwater-java,代码行数:18,代码来源:Main.java

示例8: requestPragmaNoCache

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
@Test public void requestPragmaNoCache() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
      .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
      .addHeader("Cache-Control: max-age=60")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  assertEquals("A", get(url).body().string());
  Request request = new Request.Builder()
      .url(url)
      .header("Pragma", "no-cache")
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("B", response.body().string());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:19,代码来源:CacheTest.java

示例9: getSwitchFeaturesReply

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
protected OFFeaturesReply getSwitchFeaturesReply(DatapathId switchId) {
	IOFSwitchService switchService =
			(IOFSwitchService) getContext().getAttributes().
			get(IOFSwitchService.class.getCanonicalName());

	IOFSwitch sw = switchService.getSwitch(switchId);
	Future<OFFeaturesReply> future;
	OFFeaturesReply featuresReply = null;
	OFFeaturesRequest featuresRequest = sw.getOFFactory().buildFeaturesRequest().build();
	if (sw != null) {
		try {
			future = sw.writeRequest(featuresRequest);
			featuresReply = future.get(10, TimeUnit.SECONDS);
		} catch (Exception e) {
			log.error("Failure getting features reply from switch" + sw, e);
		}
	}

	return featuresReply;
}
 
开发者ID:nsg-ethz,项目名称:iTAP-controller,代码行数:21,代码来源:SwitchResourceBase.java

示例10: start

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
@Override
public void start ( final BundleContext bundleContext ) throws Exception
{
    this.executor = new ExportedExecutorService ( "org.eclipse.scada.ca.server.osgi", 1, 1, 1, TimeUnit.MINUTES );

    Activator.context = bundleContext;
    this.tracker = new SingleServiceTracker<ConfigurationAdministrator> ( bundleContext, ConfigurationAdministrator.class, new SingleServiceListener<ConfigurationAdministrator> () {

        @Override
        public void serviceChange ( final ServiceReference<ConfigurationAdministrator> reference, final ConfigurationAdministrator service )
        {
            setService ( service );
        }
    } );
    this.tracker.open ();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:17,代码来源:Activator.java

示例11: submitConsumeRequestLater

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
private void submitConsumeRequestLater(//
    final ProcessQueue processQueue, //
    final MessageQueue messageQueue, //
    final long suspendTimeMillis//
) {
    long timeMillis = suspendTimeMillis;
    if (timeMillis == -1) {
        timeMillis = this.defaultMQPushConsumer.getSuspendCurrentQueueTimeMillis();
    }

    if (timeMillis < 10) {
        timeMillis = 10;
    } else if (timeMillis > 30000) {
        timeMillis = 30000;
    }

    this.scheduledExecutorService.schedule(new Runnable() {

        @Override
        public void run() {
            ConsumeMessageOrderlyService.this.submitConsumeRequest(null, processQueue, messageQueue, true);
        }
    }, timeMillis, TimeUnit.MILLISECONDS);
}
 
开发者ID:lirenzuo,项目名称:rocketmq-rocketmq-all-4.1.0-incubating,代码行数:25,代码来源:ConsumeMessageOrderlyService.java

示例12: connect

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
public void connect(String url) {
  try {
    mHttpClient= (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance();
  } catch (Exception e) {
    isSupportWebSocket =false;
    return;
  }
  mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
  mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
  // Disable timeouts for read
  mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);

  Request request = new Request.Builder().url(url).build();
  WebSocketCall call = WebSocketCall.create(mHttpClient, request);
  call.enqueue(this);
}
 
开发者ID:amap-demo,项目名称:weex-3d-map,代码行数:17,代码来源:WXWebSocketManager.java

示例13: onStart

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
@Override
protected void onStart() {
    super.onStart();
    compositeSubscription.add(RxView.clicks(binding.buttonDebounce)
            .observeOn(Schedulers.computation())
            .debounce(3, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(v -> binding.textDebounceResult.setText("Debounce Completed")));

    compositeSubscription.add(RxView.clicks(binding.buttonSleep)
            .observeOn(Schedulers.io())
            .map(v -> {
                SystemClock.sleep(3000L);
                return v;
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(v -> binding.textSleepResult.setText("Sleep Completed")));
}
 
开发者ID:sumio,项目名称:RxJavaEspressoSample,代码行数:19,代码来源:RxJava1Activity.java

示例14: runCode

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
@Override
public void runCode() {
    super.runCode();
    Observable.interval(2, TimeUnit.SECONDS)
            .compose(this.bindToLifecycle())
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object num) {
                    println(count++);
                }
            });
    Observable.interval(2, TimeUnit.SECONDS)
            .compose(this.bindUntilEvent(PAUSE))
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object o) {
                    println(System.currentTimeMillis());
                }
            });
}
 
开发者ID:Aiushtha,项目名称:Go-RxJava,代码行数:21,代码来源:RxBinding_Rxlifecycle.java

示例15: getAutocomplete

import java.util.concurrent.TimeUnit; //导入依赖的package包/类
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {

        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            autocompletePredictions.release();
            return null;
        }
        return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    return null;
}
 
开发者ID:Mun0n,项目名称:MADBike,代码行数:23,代码来源:PlaceAutocompleteAdapter.java


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