本文整理匯總了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;
}
示例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);
}
}
示例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());
}
示例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;
}
}
示例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);
}
示例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();
}
}
}
示例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());
}
示例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;
}
示例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 ();
}
示例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);
}
示例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")));
}
示例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());
}
});
}
示例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;
}