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


Java AtomicInteger.incrementAndGet方法代碼示例

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


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

示例1: test

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:DelayOverflow.java

示例2: fromActionTwice

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void fromActionTwice() {
    final AtomicInteger atomicInteger = new AtomicInteger();

    Action run = new Action() {
        @Override
        public void run() throws Exception {
            atomicInteger.incrementAndGet();
        }
    };

    Maybe.fromAction(run)
        .test()
        .assertResult();

    assertEquals(1, atomicInteger.get());

    Maybe.fromAction(run)
        .test()
        .assertResult();

    assertEquals(2, atomicInteger.get());
}
 
開發者ID:akarnokd,項目名稱:RxJava3-preview,代碼行數:24,代碼來源:MaybeFromActionTest.java

示例3: requestAfterExecuteThrowingAlsoThrows

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test public void requestAfterExecuteThrowingAlsoThrows() throws IOException {
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new StringConverterFactory())
      .addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter
      .build();
  Service service = retrofit.create(Service.class);

  server.enqueue(new MockResponse());

  final AtomicInteger writeCount = new AtomicInteger();
  Object a = new Object() {
    @Override public String toString() {
      writeCount.incrementAndGet();
      throw new RuntimeException("Broken!");
    }
  };

  try {
    service.postRequestBody(a);
    fail();
  } catch (RuntimeException e) {
    assertThat(e).hasMessage("Broken!");
  }
  assertThat(writeCount.get()).isEqualTo(1);
}
 
開發者ID:jaredsburrows,項目名稱:retrofit2-synchronous-adapter,代碼行數:27,代碼來源:SynchronousCallTest.java

示例4: requestBeforeExecuteCreates

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test public void requestBeforeExecuteCreates() throws IOException {
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(server.url("/"))
      .addConverterFactory(new ToStringConverterFactory())
      .build();
  Service service = retrofit.create(Service.class);

  server.enqueue(new MockResponse());

  final AtomicInteger writeCount = new AtomicInteger();
  Object a = new Object() {
    @Override public String toString() {
      writeCount.incrementAndGet();
      return "Hello";
    }
  };
  Call<String> call = service.postRequestBody(a);

  call.request();
  assertThat(writeCount.get()).isEqualTo(1);

  call.execute();
  assertThat(writeCount.get()).isEqualTo(1);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:25,代碼來源:CallTest.java

示例5: readTag

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
/**
 * Reads a DER tag from the stream.
 * 
 * @param bytesRead Will be updated with the number of bytes read from the stream.
 * @param expectedFlags A set of DER tags that are expected.
 * @return A DER tag read from the stream.
 */
public int readTag(AtomicInteger bytesRead, DerTag... expectedFlags)
    throws DerEncodingException, IOException {

  int tag = in.read();
  bytesRead.incrementAndGet();

  if (tag < 0) {
    throw new DerEncodingException("Expected tag, got end of stream.");
  }

  for (DerTag expected : expectedFlags) {
    tag -= expected.getTag();
  }

  if (tag < 0) {
    throw new DerEncodingException("Some flags are missing resulting in a tag value of < 0.");
  }

  return tag;
}
 
開發者ID:hyperledger,項目名稱:quilt,代碼行數:28,代碼來源:DerInputStream.java

示例6: testRepeatedExecution

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的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

示例7: oneStartOnly

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void oneStartOnly() {

    final AtomicInteger startCount = new AtomicInteger();

    TestSubscriber<Integer> ts = new TestSubscriber<Integer>() {
        @Override
        public void onStart() {
            startCount.incrementAndGet();
        }
    };

    PublishProcessor<Integer> ps = PublishProcessor.create();

    ps.publish(new Function<Flowable<Integer>, Flowable<Integer>>() {
        @Override
        public Flowable<Integer> apply(Flowable<Integer> o) {
            return o.take(1);
        }
    }).subscribe(ts);

    Assert.assertEquals(1, startCount.get());
}
 
開發者ID:akarnokd,項目名稱:RxJava3-preview,代碼行數:24,代碼來源:FlowablePublishFunctionTest.java

示例8: ArrayElement

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
ArrayElement(
    final PsiElement arrayElement,
    final AtomicInteger elementIndex
) {
    if (arrayElement instanceof ArrayHashElement) {
        key = ((ArrayHashElement) arrayElement).getKey();
        value = ((ArrayHashElement) arrayElement).getValue();
    }
    else {
        key = PhpPsiElementFactory.createFromText(arrayElement.getProject(), LeafPsiElement.class, String.valueOf(elementIndex.get()));
        value = ((PhpPsiElement) arrayElement).getFirstPsiChild();
        isIndexed = true;
        elementIndex.incrementAndGet();
    }
}
 
開發者ID:rentalhost,項目名稱:laravel-insight,代碼行數:16,代碼來源:ArrayAdapter.java

示例9: process

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
/**
    *
    * @param id The id to check for ratelimits
    * @return false if the id is ratelimited
    */
public boolean process(String id) {
	AtomicInteger currentLimit = idsRateLimited.computeIfAbsent(id, k -> new AtomicInteger());
	if (currentLimit.get() >= max) return false;
	currentLimit.incrementAndGet();
	TASK_PROCESSOR.addTask(System.currentTimeMillis() + timeout, currentLimit::decrementAndGet);
	return true;
}
 
開發者ID:BRjDevs,項目名稱:BRjLibs,代碼行數:13,代碼來源:RateLimiter.java

示例10: pgNotify

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
void pgNotify() throws InterruptedException {
    DatabaseWrapper wrapper = new DatabaseWrapper(requireConnection());

    int interval = 100;
    String channel = "foo";
    String payload = "bar";

    AtomicInteger exceptions = new AtomicInteger(0);
    NotificationService ns = new NotificationService(getTestJdbcUrl(), NotifyTest.class.getSimpleName(),
            interval, e -> exceptions.incrementAndGet());

    AtomicInteger notifications = new AtomicInteger(0);
    AtomicBoolean isBar = new AtomicBoolean(false);
    ns.addListener(notification -> {
        notifications.getAndIncrement();
        isBar.set(notification.getParameter().equals(payload));
    }, channel);

    Thread.sleep(interval * 2);
    wrapper.notif(channel, payload);
    Thread.sleep(interval * 2);

    Assertions.assertEquals(0, exceptions.get(), "NotificationService threw exceptions");
    Assertions.assertEquals(1, notifications.get(), "Did not receive notification");
    Assertions.assertTrue(isBar.get(), "Payload was wrong");
    ns.shutdown();
}
 
開發者ID:napstr,項目名稱:SqlSauce,代碼行數:29,代碼來源:NotifyTest.java

示例11: multipleHandlers

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void multipleHandlers()
{
  final SpyImpl support = new SpyImpl( new ArezContext() );

  final Object event = new Object();

  final AtomicInteger callCount1 = new AtomicInteger();
  final AtomicInteger callCount2 = new AtomicInteger();
  final AtomicInteger callCount3 = new AtomicInteger();

  final SpyEventHandler handler1 = e -> callCount1.incrementAndGet();
  final SpyEventHandler handler2 = e -> callCount2.incrementAndGet();
  final SpyEventHandler handler3 = e -> callCount3.incrementAndGet();
  support.addSpyEventHandler( handler1 );
  support.addSpyEventHandler( handler2 );
  support.addSpyEventHandler( handler3 );

  assertEquals( support.getSpyEventHandlers().size(), 3 );

  support.reportSpyEvent( event );

  assertEquals( callCount1.get(), 1 );
  assertEquals( callCount2.get(), 1 );
  assertEquals( callCount3.get(), 1 );

  support.reportSpyEvent( event );

  assertEquals( callCount1.get(), 2 );
  assertEquals( callCount2.get(), 2 );
  assertEquals( callCount3.get(), 2 );
}
 
開發者ID:arez,項目名稱:arez,代碼行數:33,代碼來源:SpyImplTest.java

示例12: dispose_releasesResources

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
@Test
public void dispose_releasesResources()
  throws Throwable
{
  final ArezContext context = Arez.context();

  final Observable observable = context.createObservable();

  final AtomicBoolean result = new AtomicBoolean();

  final AtomicInteger conditionRun = new AtomicInteger();
  final AtomicInteger effectRun = new AtomicInteger();

  final String name = ValueUtil.randomString();
  final boolean mutation = true;
  final SafeFunction<Boolean> condition = () -> {
    conditionRun.incrementAndGet();
    observable.reportObserved();
    return result.get();
  };
  final SafeProcedure procedure = effectRun::incrementAndGet;

  final Watcher watcher = new Arez_Watcher( name, mutation, condition, procedure );

  assertEquals( conditionRun.get(), 1 );
  assertEquals( effectRun.get(), 0 );
  assertEquals( Disposable.isDisposed( watcher ), false );

  result.set( true );
  Disposable.dispose( watcher );

  assertEquals( Disposable.isDisposed( watcher ), true );

  context.action( ValueUtil.randomString(), true, observable::reportChanged );

  assertEquals( conditionRun.get(), 1 );
  assertEquals( effectRun.get(), 0 );
}
 
開發者ID:arez,項目名稱:arez,代碼行數:39,代碼來源:WatcherTest.java

示例13: testReschedule

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
/**
 * Test to make sure we reschedule the task for execution if it has already in progress.
 */
@Test
public void testReschedule() throws Exception {
  ScheduledExecutorService ex = Executors.newScheduledThreadPool(1);
  OneTaskOnlyExecutor decorator = new OneTaskOnlyExecutor(ex);

  final CountDownLatch taskRunning = new CountDownLatch(1);
  final CountDownLatch continueTask = new CountDownLatch(1);
  final AtomicInteger counter = new AtomicInteger();

  Callable waitForLatch = new Callable() {

    public Object call() throws Exception {
      taskRunning.countDown();
      continueTask.await();
      counter.incrementAndGet();
      return null;
    }
  };

  Runnable increment = new Runnable() {

    public void run() {
      counter.incrementAndGet();
    }
  };

  decorator.schedule(waitForLatch, 0, TimeUnit.SECONDS);
  taskRunning.await();
  decorator.schedule(increment, 0, TimeUnit.SECONDS);

  assertEquals(0, counter.get());
  continueTask.countDown();

  ex.shutdown();
  ex.awaitTermination(60, TimeUnit.SECONDS);
  assertEquals(2, counter.get());
}
 
開發者ID:ampool,項目名稱:monarch,代碼行數:41,代碼來源:OneTaskOnlyDecoratorJUnitTest.java

示例14: checkNodes

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
public static void checkNodes(Ethereum ethereum, CommonConfig commonConfig, AtomicInteger fatalErrors) {
    try {
        Source<byte[], byte[]> stateDS = commonConfig.stateSource();
        byte[] stateRoot = ethereum.getBlockchain().getBestBlock().getHeader().getStateRoot();
        Integer rootsSize = getReferencedTrieNodes(stateDS, true, stateRoot);
        testLogger.info("Node validation successful");
        testLogger.info("Non-unique node size: {}", rootsSize);
    } catch (Exception | AssertionError ex) {
        testLogger.error("Node validation error", ex);
        fatalErrors.incrementAndGet();
    }
}
 
開發者ID:talentchain,項目名稱:talchain,代碼行數:13,代碼來源:BlockchainValidation.java

示例15: run

import java.util.concurrent.atomic.AtomicInteger; //導入方法依賴的package包/類
void run() throws Exception {
    final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    final ObjectName observedName = new ObjectName("a:b=c");
    final ObjectName monitorName = new ObjectName("a:type=Monitor");
    mbs.registerMBean(new StringMonitor(), monitorName);
    final StringMonitorMBean monitorProxy =
        JMX.newMBeanProxy(mbs, monitorName, StringMonitorMBean.class);
    final TestMBean observedProxy =
        JMX.newMBeanProxy(mbs, observedName, TestMBean.class);

    final Runnable sensitiveThing = new Runnable() {
        public void run() {
            doSensitiveThing(monitorProxy, observedName);
        }
    };

    final Runnable nothing = new Runnable() {
        public void run() {}
    };

    final Runnable withinGetAttribute =
        (when == When.IN_GET_ATTRIBUTE) ? sensitiveThing : nothing;

    mbs.registerMBean(new Test(withinGetAttribute), observedName);
    monitorProxy.addObservedObject(observedName);
    monitorProxy.setObservedAttribute("Thing");
    monitorProxy.setStringToCompare("old");
    monitorProxy.setGranularityPeriod(10L); // 10 ms
    monitorProxy.setNotifyDiffer(true);

    final int initGetCount = observedProxy.getGetCount();
    monitorProxy.start();

    int getCount = initGetCount;
    for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
        getCount = observedProxy.getGetCount();
        if (getCount != initGetCount)
            break;
        Thread.sleep(10);
    }
    if (getCount <= initGetCount)
        throw new Exception("Test failed: presumable deadlock");
    // This won't show up as a deadlock in CTRL-\ or in
    // ThreadMXBean.findDeadlockedThreads(), because they don't
    // see that thread A is waiting for thread B (B.join()), and
    // thread B is waiting for a lock held by thread A

    // Now we know the monitor has observed the initial value,
    // so if we want to test notify behaviour we can trigger by
    // exceeding the threshold.
    if (when == When.IN_NOTIFY) {
        final AtomicInteger notifCount = new AtomicInteger();
        final NotificationListener listener = new NotificationListener() {
            public void handleNotification(Notification n, Object h) {
                Thread t = new Thread(sensitiveThing);
                t.start();
                try {
                    t.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                notifCount.incrementAndGet();
            }
        };
        mbs.addNotificationListener(monitorName, listener, null, null);
        observedProxy.setThing("new");
        for (int i = 0; i < 500 && notifCount.get() == 0; i++)
            Thread.sleep(10);
        if (notifCount.get() == 0)
            throw new Exception("Test failed: presumable deadlock");
    }

}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:74,代碼來源:StringMonitorDeadlockTest.java


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