java.lang.Thread.yield()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(5.9k)|赞(0)|评价(0)|浏览(144)

本文整理了Java中java.lang.Thread.yield()方法的一些代码示例,展示了Thread.yield()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Thread.yield()方法的具体详情如下:
包路径:java.lang.Thread
类名称:Thread
方法名:yield

Thread.yield介绍

[英]A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.

Yield is a heuristic attempt to improve relative progression between threads that would otherwise over-utilise a CPU. Its use should be combined with detailed profiling and benchmarking to ensure that it actually has the desired effect.

It is rarely appropriate to use this method. It may be useful for debugging or testing purposes, where it may help to reproduce bugs due to race conditions. It may also be useful when designing concurrency control constructs such as the ones in the java.util.concurrent.locks package.
[中]向调度程序发出的提示,表示当前线程愿意使用处理器。调度程序可以随意忽略此提示。
产量是一种启发式尝试,旨在改善线程之间的相对进度,否则会过度使用CPU。它的使用应该与详细的分析和基准测试相结合,以确保它实际具有预期的效果。
使用这种方法很少合适。它可能对调试或测试有用,因为它可能有助于重现由于竞争条件而产生的bug。在设计并发控制结构(如java中的结构)时,它可能也很有用。util。同时发生的锁上包裹。

代码示例

代码示例来源:origin: ReactiveX/RxJava

@Override
  public void run() {
    Thread.yield();
  }
},

代码示例来源:origin: libgdx/libgdx

public static void yield () {
    Thread.yield();
  }
}

代码示例来源:origin: libgdx/libgdx

public static void yield () {
    Thread.yield();
  }
}

代码示例来源:origin: google/guava

@Override
 public Integer get() {
  int nextValue = counter + 1;
  Thread.yield();
  counter = nextValue;
  return counter;
 }
};

代码示例来源:origin: log4j/log4j

public void run() {
  Thread.yield();
  pause(delay);
  _logMonitorFrame.setVisible(true);
 }
});

代码示例来源:origin: google/guava

public void run() {
  while (!shutdown.get()) {
   interruptee.interrupt();
   Thread.yield();
  }
 }
});

代码示例来源:origin: google/guava

static void awaitWaiting(Thread t) {
 while (true) {
  Thread.State state = t.getState();
  switch (state) {
   case RUNNABLE:
   case BLOCKED:
    Thread.yield();
    break;
   case WAITING:
    return;
   default:
    throw new AssertionError("unexpected state: " + state);
  }
 }
}

代码示例来源:origin: google/guava

/** Wait for the given thread to reach the {@link State#TIMED_WAITING} thread state. */
void awaitTimedWaiting(Thread thread) {
 while (true) {
  switch (thread.getState()) {
   case BLOCKED:
   case NEW:
   case RUNNABLE:
   case WAITING:
    Thread.yield();
    break;
   case TIMED_WAITING:
    return;
   case TERMINATED:
   default:
    throw new AssertionError();
  }
 }
}

代码示例来源:origin: google/guava

/**
 * Delays, via Thread.sleep, for the given millisecond delay, but if the sleep is shorter than
 * specified, may re-sleep or yield until time elapses.
 */
static void delay(long millis) throws InterruptedException {
 long startTime = System.nanoTime();
 long ns = millis * 1000 * 1000;
 for (; ; ) {
  if (millis > 0L) Thread.sleep(millis);
  else // too short to sleep
  Thread.yield();
  long d = ns - (System.nanoTime() - startTime);
  if (d > 0L) millis = d / (1000 * 1000);
  else break;
 }
}

代码示例来源:origin: google/guava

public void realRun() {
  while (!a.compareAndSet(0, 2.0, 3.0)) {
   Thread.yield();
  }
 }
});

代码示例来源:origin: google/guava

public void realRun() {
  while (!at.compareAndSet(2.0, 3.0)) {
   Thread.yield();
  }
 }
});

代码示例来源:origin: google/guava

void shutdown() {
  shutdown.set(true);
  while (this.isAlive()) {
   Thread.yield();
  }
 }
}

代码示例来源:origin: google/guava

@Override
 public Boolean get() {
  // Check that this method is called exactly once, by the first
  // thread to synchronize.
  long t0 = System.nanoTime();
  while (waitingThreads() != numThreads - 1) {
   if (System.nanoTime() - t0 > timeout) {
    thrown.set(
      new TimeoutException(
        "timed out waiting for other threads to block"
          + " synchronizing on supplier"));
    break;
   }
   Thread.yield();
  }
  count.getAndIncrement();
  return Boolean.TRUE;
 }
};

代码示例来源:origin: google/guava

void awaitWaiting() {
 while (!isBlocked()) {
  if (getState() == State.TERMINATED) {
   throw new RuntimeException("Thread exited");
  }
  Thread.yield();
 }
}

代码示例来源:origin: google/guava

void awaitWaiting() {
 while (!isBlocked()) {
  if (getState() == State.TERMINATED) {
   throw new RuntimeException("Thread exited");
  }
  Thread.yield();
 }
}

代码示例来源:origin: google/guava

private void assertUninterruptibleDrained(BlockingQueue<Object> q) {
 assertEquals(0, Queues.drainUninterruptibly(q, ImmutableList.of(), 0, 10, MILLISECONDS));
 // but does the wait actually occurs?
 @SuppressWarnings("unused") // go/futurereturn-lsc
 Future<?> possiblyIgnoredError = threadPool.submit(new Interrupter(currentThread()));
 Stopwatch timer = Stopwatch.createStarted();
 Queues.drainUninterruptibly(q, newArrayList(), 1, 10, MILLISECONDS);
 assertThat(timer.elapsed(MILLISECONDS)).isAtLeast(10L);
 // wait for interrupted status and clear it
 while (!Thread.interrupted()) {
  Thread.yield();
 }
}

代码示例来源:origin: google/guava

/**
 * Spin-waits up to the specified number of milliseconds for the given thread to enter a wait
 * state: BLOCKED, WAITING, or TIMED_WAITING.
 */
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
 long startTime = System.nanoTime();
 for (; ; ) {
  Thread.State s = thread.getState();
  if (s == Thread.State.BLOCKED || s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING)
   return;
  else if (s == Thread.State.TERMINATED) fail("Unexpected thread termination");
  else if (millisElapsedSince(startTime) > timeoutMillis) {
   threadAssertTrue(thread.isAlive());
   return;
  }
  Thread.yield();
 }
}

代码示例来源:origin: ReactiveX/RxJava

@Override
public void subscribe(final Subscriber<? super Integer> subscriber) {
  BooleanSubscription bs = new BooleanSubscription();
  subscriber.onSubscribe(bs);
  for (int i = 1; i <= 5; i++) {
    if (bs.isCancelled()) {
      break;
    }
    numEmitted.incrementAndGet();
    subscriber.onNext(i);
    Thread.yield();
  }
  subscriber.onComplete();
}

代码示例来源:origin: ReactiveX/RxJava

@Override
public void subscribe(final Observer<? super Integer> o) {
  Disposable d = Disposables.empty();
  o.onSubscribe(d);
  for (int i = 1; i <= 5; i++) {
    if (d.isDisposed()) {
      break;
    }
    numEmitted.incrementAndGet();
    o.onNext(i);
    Thread.yield();
  }
  o.onComplete();
}

代码示例来源:origin: apache/kafka

@Test
public void testHeartbeatThreadClose() throws Exception {
  ConsumerCoordinator coordinator = prepareCoordinatorForCloseTest(true, true, true);
  coordinator.ensureActiveGroup();
  time.sleep(heartbeatIntervalMs + 100);
  Thread.yield(); // Give heartbeat thread a chance to attempt heartbeat
  closeVerifyTimeout(coordinator, Long.MAX_VALUE, requestTimeoutMs, requestTimeoutMs);
  Thread[] threads = new Thread[Thread.activeCount()];
  int threadCount = Thread.enumerate(threads);
  for (int i = 0; i < threadCount; i++)
    assertFalse("Heartbeat thread active after close", threads[i].getName().contains(groupId));
}

相关文章