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


Java AtomicBoolean.set方法代码示例

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


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

示例1: testHangReportNotSuppressedOnLongRunningFutureCancelled

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void testHangReportNotSuppressedOnLongRunningFutureCancelled() {
	getFactory().setHangDetectionTimeout(Duration.ofMillis(10));
	AtomicBoolean hangReported = new AtomicBoolean(false);
	getContext().onReportHang = (hangDuration, iterations, id) -> hangReported.set(true);
	CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

	JoinableFuture<?> task = getFactory().runAsync(
		() -> Async.awaitAsync(Async.delayAsync(Duration.ofMillis(40), cancellationTokenSource.getToken())),
		EnumSet.of(JoinableFutureCreationOption.LONG_RUNNING));

	JoinableFutureCollection taskCollection = new JoinableFutureCollection(getFactory().getContext());
	taskCollection.add(task);

	getFactory().run(() -> Async.usingAsync(
		taskCollection.join(),
		tempJoin -> {
			cancellationTokenSource.cancel();
			return Async.awaitAsync(
				TplExtensions.noThrowAwaitable(task.joinAsync()),
				() -> Async.awaitAsync(Async.delayAsync(Duration.ofMillis(40))));
		}));

	Assert.assertTrue(hangReported.get());
}
 
开发者ID:tunnelvisionlabs,项目名称:java-threading,代码行数:26,代码来源:JoinableFutureContextTest.java

示例2: testGetItemsIsCalledIncreasing

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void testGetItemsIsCalledIncreasing() {
  final AtomicBoolean called = new AtomicBoolean(false);
  final AtomicInteger calledCount = new AtomicInteger();

  ListPreloaderAdapter preloaderAdapter = new ListPreloaderAdapter() {
    @Override
    public List<Object> getPreloadItems(int position) {
      called.set(true);
      final int count = calledCount.getAndIncrement();
      assertEquals(11 + count, position);
      return super.getPreloadItems(position);
    }
  };
  ListPreloader<Object> preloader = new ListPreloader<>(requestManager,
      preloaderAdapter, preloaderAdapter, 10);
  preloader.onScroll(null, 1, 10, 30);
  assertEquals(10, calledCount.get());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:20,代码来源:ListPreloaderTest.java

示例3: shouldFlushRecordCollectorOnFlushState

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void shouldFlushRecordCollectorOnFlushState() throws Exception {
    final AtomicBoolean flushed = new AtomicBoolean(false);
    final StreamsMetrics streamsMetrics = new MockStreamsMetrics(new Metrics());
    final StreamTask streamTask = new StreamTask(taskId00, "appId", partitions, topology, consumer,
        changelogReader, config, streamsMetrics, stateDirectory, null, time, producer) {

        @Override
        RecordCollector createRecordCollector() {
            return new NoOpRecordCollector() {
                @Override
                public void flush() {
                    flushed.set(true);
                }
            };
        }
    };
    streamTask.flushState();
    assertTrue(flushed.get());
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:21,代码来源:StreamTaskTest.java

示例4: testCheckWidgetCalledFromNonMainThread

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void testCheckWidgetCalledFromNonMainThread() throws InterruptedException, TimeoutException {
	TestObserver<?> testObserver = getEmptySubscribedTestObserver();

	AtomicBoolean atomic = new AtomicBoolean(false);

	Thread thread = new Thread(() -> {
		boolean checkWidget = Preconditions.checkWidget(testObserver, shell);

		assertThat(checkWidget, is(false));

		testObserver.assertError(IllegalStateException.class);
		testObserver.assertErrorMessage(
				"Expected to be called on the main thread but was " + Thread.currentThread().getName());
		atomic.set(true);
	});
	thread.start();

	await().untilTrue(atomic);
}
 
开发者ID:SimonScholz,项目名称:RxSWT,代码行数:21,代码来源:PreconditionsTest.java

示例5: respondException

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void respondException() throws CheckedFutureException {
  AtomicInteger result = new AtomicInteger(-1);
  AtomicBoolean failure = new AtomicBoolean(false);
  final Responder<Integer> r = new Responder<Integer>() {
    @Override
    public void onException(Throwable ex) {
      failure.set(true);
      throw new NullPointerException();
    }

    @Override
    public void onValue(Integer value) {
      result.set(value);
      throw new NullPointerException();
    }
  };
  Future.value(1).respond(r);
  assertEquals(1, result.get());
  assertFalse(failure.get());
}
 
开发者ID:traneio,项目名称:future,代码行数:22,代码来源:ValueFutureTest.java

示例6: waitForChange_runWithRealmThread

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void waitForChange_runWithRealmThread() throws InterruptedException {
    final CountDownLatch bgRealmStarted = new CountDownLatch(1);
    final CountDownLatch bgRealmFished = new CountDownLatch(1);
    final AtomicBoolean bgRealmChangeResult = new AtomicBoolean(false);
    final AtomicLong bgRealmResultSize = new AtomicLong(0);

    RealmThread thread = new RealmThread(realmConfig, new RealmThread.RealmRunnable() {
        @Override
        public void run(Realm realm) {
            bgRealmStarted.countDown();
            bgRealmChangeResult.set(realm.waitForChange());
            bgRealmResultSize.set(realm.where(AllTypes.class).count());
            realm.close();
            bgRealmFished.countDown();
        }
    });
    thread.start();

    TestHelper.awaitOrFail(bgRealmStarted);
    populateTestRealm();
    TestHelper.awaitOrFail(bgRealmFished);
    assertTrue(bgRealmChangeResult.get());
    assertEquals(TEST_DATA_SIZE, bgRealmResultSize.get());
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:26,代码来源:RealmTests.java

示例7: tAtomicBoolean

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
public void tAtomicBoolean() {
    System.currentTimeMillis();
    AtomicBoolean atomic = new AtomicBoolean();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < 10000000; i++) {
        if (atomic.compareAndSet(false, true)) {
            try {
                // ...
            } finally {
                atomic.set(false);
            }
        }
    }
    long t2 = System.currentTimeMillis();

    System.out.println("take time:" + (t2 - t1) + " ms.");
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:19,代码来源:LockPerfMain.java

示例8: duplicatesNoChange

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void duplicatesNoChange() {
	final AtomicBoolean wasCalled = new AtomicBoolean();
	columnMetaData.get(1).setName("att1");
	columnMetaData.get(2).setName("att1");
	columnMetaData.get(3).setName("att2");
	columnMetaData.add(new DefaultColumnMetaData("att2", ColumnType.BINARY));
	validator.init(columnMetaData);
	Observer<Set<Integer>> observer = new Observer<Set<Integer>>() {

		@Override
		public void update(Observable<Set<Integer>> observable, Set<Integer> arg) {
			wasCalled.set(true);
		}
	};
	validator.addObserver(observer, false);
	validator.validate(0);
	assertFalse(wasCalled.get());
}
 
开发者ID:transwarpio,项目名称:rapidminer,代码行数:20,代码来源:ConfigureDataValidatorTest.java

示例9: appendAlterSQL

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Override
public boolean appendAlterSQL(PgStatement newCondition, StringBuilder sb,
        AtomicBoolean isNeedDepcies) {
    final int startLength = sb.length();
    if (!(newCondition instanceof PgTable)) {
        return false;
    }

    PgTable newTable = (PgTable)newCondition;

    if (isNeedRecreate(newTable)) {
        isNeedDepcies.set(true);
        return true;
    }

    compareTableTypes(newTable, sb);
    compareInherits(newTable, sb);
    compareOptions(newTable, sb);
    compareOwners(newTable, sb);
    compareTableOptions(newTable, sb);
    alterPrivileges(newTable, sb);
    compareComment(newTable,sb);

    return sb.length() > startLength;
}
 
开发者ID:pgcodekeeper,项目名称:pgcodekeeper,代码行数:26,代码来源:PgTable.java

示例10: startStartsServerWithServices

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Test
public void startStartsServerWithServices() throws Exception {
    final int port = ThreadLocalRandom.current().nextInt(1000, 10000);
    final int serviceCount = ThreadLocalRandom.current().nextInt(5, 10);
    final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000);

    final ApplicationContext applicationContext = mock(ApplicationContext.class);
    final Server server = mock(Server.class, new TriesToReturnSelf());
    when(server.getPort()).thenReturn(port);

    final Map<String, Object> services = IntStream.range(0, serviceCount)
            .mapToObj(i -> mock(BindableService.class))
            .collect(Collectors.toMap(s -> UUID.randomUUID().toString(), s -> s));

    AtomicBoolean built = new AtomicBoolean(false);

    GrpcServerFactory fakeFactory = (p, s) -> {
        built.set(true);
        assertThat(p).isEqualTo(port);
        s.forEach(ss -> assertThat(services.values().contains(ss)).isTrue());
        return server;
    };

    when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(services);

    GrpcServerHost runner = new GrpcServerHost(port, shutdownWaitTimeInMillis, fakeFactory);
    runner.setApplicationContext(applicationContext);

    runner.start();
    assertThat(built.get()).isTrue();

    verify(server).start();

    assertThat(runner.server()).isEqualTo(server);
}
 
开发者ID:salesforce,项目名称:grpc-java-contrib,代码行数:36,代码来源:GrpcServerHostTest.java

示例11: main

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
public static void main(String[] args) throws Throwable {
    final ForkJoinPool e = new ForkJoinPool(1);
    final AtomicBoolean b = new AtomicBoolean();
    final Runnable setFalse = () -> b.set(false);
    for (int i = 0; i < 100000; i++) {
        b.set(true);
        e.execute(setFalse);
        long st = System.nanoTime();
        while (b.get()) {
            if (System.nanoTime() - st >= TimeUnit.SECONDS.toNanos(10)) {
                throw new RuntimeException("Submitted task failed to execute");
            }
        }
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:16,代码来源:SubmissionTest.java

示例12: testToString

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
/**
 * toString returns current value.
 */
public void testToString() {
    AtomicBoolean ai = new AtomicBoolean();
    assertEquals(Boolean.toString(false), ai.toString());
    ai.set(true);
    assertEquals(Boolean.toString(true), ai.toString());
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:AtomicBooleanTest.java

示例13: testCustomSchedule_startStop

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
public void testCustomSchedule_startStop() throws Exception {
  final CyclicBarrier firstBarrier = new CyclicBarrier(2);
  final CyclicBarrier secondBarrier = new CyclicBarrier(2);
  final AtomicBoolean shouldWait = new AtomicBoolean(true);
  Runnable task = new Runnable() {
    @Override public void run() {
      try {
        if (shouldWait.get()) {
          firstBarrier.await();
          secondBarrier.await();
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  };
  TestCustomScheduler scheduler = new TestCustomScheduler();
  Future<?> future = scheduler.schedule(null, Executors.newScheduledThreadPool(10), task);
  firstBarrier.await();
  assertEquals(1, scheduler.scheduleCounter.get());
  secondBarrier.await();
  firstBarrier.await();
  assertEquals(2, scheduler.scheduleCounter.get());
  shouldWait.set(false);
  secondBarrier.await();
  future.cancel(false);
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:28,代码来源:AbstractScheduledServiceTest.java

示例14: getFreeVariables

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@Override
public TCNameSet getFreeVariables(Environment globals, Environment env, AtomicBoolean returns)
{
	returns.set(true);

	if (expression == null)
	{
		return new TCNameSet();
	}
	
	return expression.getFreeVariables(globals, env);
}
 
开发者ID:nickbattle,项目名称:FJ-VDMJ,代码行数:13,代码来源:TCExitStatement.java

示例15: testTransformAsync_asyncFunction_cancelledBeforeApplyingFunction

import java.util.concurrent.atomic.AtomicBoolean; //导入方法依赖的package包/类
@GwtIncompatible // threads

  public void testTransformAsync_asyncFunction_cancelledBeforeApplyingFunction()
      throws InterruptedException {
    final AtomicBoolean functionCalled = new AtomicBoolean();
    AsyncFunction<String, Integer> function = new AsyncFunction<String, Integer>() {
      @Override
      public ListenableFuture<Integer> apply(String input) throws Exception {
        functionCalled.set(true);
        return immediateFuture(1);
      }
    };
    SettableFuture<String> inputFuture = SettableFuture.create();
    ExecutorService executor = newSingleThreadExecutor();
    ListenableFuture<Integer> future = transformAsync(
        inputFuture, function, executor);

    // Pause the executor.
    final CountDownLatch beforeFunction = new CountDownLatch(1);
    executor.submit(new Runnable() {
      @Override
      public void run() {
        awaitUninterruptibly(beforeFunction);
      }
    });

    // Cancel the future after making input available.
    inputFuture.set("value");
    future.cancel(false);

    // Unpause the executor.
    beforeFunction.countDown();
    executor.awaitTermination(5, SECONDS);

    assertFalse(functionCalled.get());
  }
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:37,代码来源:FuturesTest.java


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