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


Java LockSupport类代码示例

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


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

示例1: notifyClusterDDL

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void notifyClusterDDL(String schema, String table, String sql, DDLInfo.DDLStatus ddlStatus, boolean needNotifyOther) throws Exception {
    CuratorFramework zkConn = ZKUtils.getConnection();
    DDLInfo ddlInfo = new DDLInfo(schema, sql, ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID), ddlStatus);
    String nodeName = StringUtil.getFullName(schema, table);
    String nodePath = ZKPaths.makePath(KVPathUtil.getDDLPath(), nodeName);
    if (zkConn.checkExists().forPath(nodePath) == null) {
        zkConn.create().forPath(nodePath, ddlInfo.toString().getBytes(StandardCharsets.UTF_8));
    } else {
        String instancePath = ZKPaths.makePath(nodePath, KVPathUtil.DDL_INSTANCE);
        String thisNode = ZkConfig.getInstance().getValue(ZkParamCfg.ZK_CFG_MYID);
        ZKUtils.createTempNode(instancePath, thisNode);
        if (needNotifyOther) {
            //this node is ddl sender
            zkConn.setData().forPath(nodePath, ddlInfo.toString().getBytes(StandardCharsets.UTF_8));
            while (true) {
                List<String> preparedList = zkConn.getChildren().forPath(instancePath);
                List<String> onlineList = zkConn.getChildren().forPath(KVPathUtil.getOnlinePath());
                if (preparedList.size() >= onlineList.size()) {
                    zkConn.delete().deletingChildrenIfNeeded().forPath(nodePath);
                    break;
                }
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(100));
            }
        }
    }
}
 
开发者ID:actiontech,项目名称:dble,代码行数:27,代码来源:ProxyMetaManager.java

示例2: ensureSyncComplete

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void ensureSyncComplete(int blockIndex) {
    final AtomicLong noSyncLength = noSyncLengthMap.get(blockIndex);
    if (noSyncLength != null && noSyncLength.get() > 0) {
        // sync to store
        if (syncRunning) {
            // wait for sync
            parkThreadList.add(Thread.currentThread());
            while (true) {
                LockSupport.parkNanos(WAIT_SYNC_NANO);
                if (!syncRunning) break;
            }
        }

        // sync once, make sure data has been synced.
        syncRunning = true;
        syncRunnable.run();

    }
}
 
开发者ID:lingochamp,项目名称:okdownload,代码行数:20,代码来源:MultiPointOutputStream.java

示例3: testCircuitBreaker

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
@Test
public void testCircuitBreaker() {


    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
            .failureRateThreshold(25)
            .waitDurationInOpenState(Duration.ofMillis(1000))
            .ringBufferSizeInHalfOpenState(1)
            .ringBufferSizeInClosedState(2)
            .build();

    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("test");

    Observable.interval(500,TimeUnit.MILLISECONDS).map(i -> {
        if(1==1) throw new RuntimeException("BAM");
        return "result"+i;
    })
            .lift(CircuitBreakerOperator.of(circuitBreaker)).map(result -> result)
            .subscribe(System.out::println);


    LockSupport.park();

}
 
开发者ID:noorulhaq,项目名称:reactive.loanbroker.system,代码行数:25,代码来源:Javaslang2CircuitBreakerTests.java

示例4: main

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public static void main(String[] args) throws InterruptedException{
    new Thread(){
        @Override
        public void run() {
            long writeLong=lock.writeLock();
            LockSupport.parkNanos(600000000000L);
            lock.unlockWrite(writeLong);
        }
    }.start();
    Thread.sleep(100);
    for(int i=0;i<3;++i){
        holdCpuThreads[i]=new Thread(new HoldCPUReadThread());
        holdCpuThreads[i].start();
    }
    Thread.sleep(10000);

    //线程中断后,会占用CPU
    for(int i=0;i<3;++i){
        holdCpuThreads[i].interrupt();
    }
    int aa=0;
}
 
开发者ID:sean417,项目名称:LearningOfThinkInJava,代码行数:23,代码来源:StampedLockCPUDemo.java

示例5: contendedLock

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
 * Possibly blocks awaiting root lock.
 */
private final void contendedLock() {
    boolean waiting = false;
    for (int s;;) {
        if (((s = lockState) & ~WAITER) == 0) {
            if (U.compareAndSetInt(this, LOCKSTATE, s, WRITER)) {
                if (waiting)
                    waiter = null;
                return;
            }
        }
        else if ((s & WAITER) == 0) {
            if (U.compareAndSetInt(this, LOCKSTATE, s, s | WAITER)) {
                waiting = true;
                waiter = Thread.currentThread();
            }
        }
        else if (waiting)
            LockSupport.park(this);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:ConcurrentHashMap.java

示例6: handle

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public Reply handle(Command command) {
    switch (command.code()) {
        case Command.START:
            return handleStart((StartCommand) command);
        case Command.STOP:
            return handleStop((StopCommand) command);
    }
    LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(responseLag));
    switch (command.code()) {
        case Command.ECHO:
            return handleEcho((EchoCommand) command);
        case Command.COUNT:
            return handleCount((CountCommand) command);
        case Command.REVERSE:
            return handleReverse((ReverseCommand) command);
        case Command.LOWER_CAST:
            return handleLowerCast((LowerCastCommand) command);
        case Command.UPPER_CAST:
            return handleUpperCast((UpperCastCommand) command);
        default:
            throw new IllegalStateException();
    }
}
 
开发者ID:altiplanogao,项目名称:io-comparison,代码行数:24,代码来源:ServerCommandHandler.java

示例7: finishCompletion

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
 * Removes and signals all waiting threads, invokes done(), and
 * nulls out callable.
 */
private void finishCompletion() {
    // assert state > COMPLETING;
    for (WaitNode q; (q = waiters) != null;) {
        if (WAITERS.weakCompareAndSet(this, q, null)) {
            for (;;) {
                Thread t = q.thread;
                if (t != null) {
                    q.thread = null;
                    LockSupport.unpark(t);
                }
                WaitNode next = q.next;
                if (next == null)
                    break;
                q.next = null; // unlink to help gc
                q = next;
            }
            break;
        }
    }

    done();

    callable = null;        // to reduce footprint
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:FutureTask.java

示例8: applyWaitMethod

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
private int applyWaitMethod(final SequenceBarrier barrier, int counter)
        throws AlertException {
    //检查是否需要终止
    barrier.checkAlert();
    //如果在200~100,重试
    if (counter > 100) {
        --counter;
    }
    //如果在100~0,调用Thread.yield()让出CPU
    else if (counter > 0) {
        --counter;
        Thread.yield();
    }
    //<0的话,利用LockSupport.parkNanos(1L)来sleep最小时间
    else {
        LockSupport.parkNanos(1L);
    }
    return counter;
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:20,代码来源:SleepingWaitStrategy.java

示例9: testRemoveWaiter_interruption

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void testRemoveWaiter_interruption() throws Exception {
  final AbstractFuture<String> future = new AbstractFuture<String>() {};
  WaiterThread waiter1 = new WaiterThread(future);
  waiter1.start();
  waiter1.awaitWaiting();

  WaiterThread waiter2 = new WaiterThread(future);
  waiter2.start();
  waiter2.awaitWaiting();
  // The waiter queue should be waiter2->waiter1

  // This should wake up waiter1 and cause the waiter1 node to be removed.
  waiter1.interrupt();

  waiter1.join();
  waiter2.awaitWaiting();  // should still be blocked

  LockSupport.unpark(waiter2);  // spurious wakeup
  waiter2.awaitWaiting();  // should eventually re-park

  future.set(null);
  waiter2.join();
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:24,代码来源:AbstractFutureTest.java

示例10: testCpu

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public static void testCpu(){
        long startTime = System.currentTimeMillis();
        System.out.println(System.currentTimeMillis());
        int number = 0;
        while (true){
            LockSupport.unpark(Thread.currentThread());
//            LockSupport.park();
            ++number;
            long currTime = System.currentTimeMillis();
            if(number % 10000 == 0) {
                LockSupport.park();
                System.out.println("运行次数" + number + "时间" + (currTime - startTime));
            }
        }

    }
 
开发者ID:jwpttcg66,项目名称:game-executor,代码行数:17,代码来源:TestLockSupport.java

示例11: testParkAfterUnpark

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
public void testParkAfterUnpark(final ParkMethod parkMethod) {
    final CountDownLatch pleaseUnpark = new CountDownLatch(1);
    final AtomicBoolean pleasePark = new AtomicBoolean(false);
    Thread t = newStartedThread(new CheckedRunnable() {
        public void realRun() {
            pleaseUnpark.countDown();
            while (!pleasePark.get())
                Thread.yield();
            parkMethod.park();
        }});

    await(pleaseUnpark);
    LockSupport.unpark(t);
    pleasePark.set(true);
    awaitTermination(t);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:LockSupportTest.java

示例12: newHeaders

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
 * Enqueue a batch of message headers
 *
 * @param p_headers
 *         the message headers
 * @param p_messages
 *         the number of used entries in array
 */
void newHeaders(final MessageHeader[] p_headers, final int p_messages) {
    // #ifdef STATISTICS
    SOP_PUSH.enter();
    // #endif /* STATISTICS */

    if (!m_defaultMessageHeaders.pushMessageHeaders(p_headers, p_messages)) {
        for (int i = 0; i < p_messages; i++) {
            while (!m_defaultMessageHeaders.pushMessageHeader(p_headers[i])) {
                // #ifdef STATISTICS
                SOP_WAIT.enter();
                // #endif /* STATISTICS */

                LockSupport.parkNanos(100);

                // #ifdef STATISTICS
                SOP_WAIT.leave();
                // #endif /* STATISTICS */
            }
        }
    }

    // #ifdef STATISTICS
    SOP_PUSH.leave();
    // #endif /* STATISTICS */
}
 
开发者ID:hhu-bsinfo,项目名称:dxram,代码行数:34,代码来源:DefaultMessageHandlerPool.java

示例13: receivedBuffer

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
@Override
public void receivedBuffer(final short p_sourceNodeId, final long p_bufferHandle, final long p_addr, final int p_length) {
    // #if LOGGER >= TRACE
    LOGGER.trace("Received buffer (0x%X, %d) from 0x%X", p_addr, p_length, p_sourceNodeId);
    // #endif /* LOGGER >= TRACE */

    IBConnection connection;
    try {
        connection = (IBConnection) getConnection(p_sourceNodeId);
    } catch (final NetworkException e) {
        // #if LOGGER >= ERROR
        LOGGER.error("Getting connection for recv buffer of node 0x%X failed", p_sourceNodeId, e);
        // #endif /* LOGGER >= ERROR */
        return;
    }

    // Avoid congestion by not allowing more than m_numberOfBuffers buffers to be cached for reading
    while (!m_incomingBufferQueue.pushBuffer(connection, null, p_bufferHandle, p_addr, p_length)) {
        // #if LOGGER == TRACE
        LOGGER.trace("Message creator: IncomingBuffer queue is full!");
        // #endif /* LOGGER == TRACE */

        //Thread.yield();
        LockSupport.parkNanos(100);
    }
}
 
开发者ID:hhu-bsinfo,项目名称:dxram,代码行数:27,代码来源:IBConnectionManager.java

示例14: waitAllSession

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
private static boolean waitAllSession(ManagerConnection c, long timeout, long beginTime) {
    logger.info("waiting all sessions of distributed transaction which are not finished.");
    List<NonBlockingSession> fcList = getNeedWaitSession();
    while (!fcList.isEmpty()) {
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
        Iterator<NonBlockingSession> sListIterator = fcList.iterator();
        while (sListIterator.hasNext()) {
            NonBlockingSession session = sListIterator.next();
            if (!session.isNeedWaitFinished()) {
                sListIterator.remove();
            }
        }
        if (c.isClosed()) {
            errMsg = "client closed while waiting for unfinished distributed transactions.";
            logger.info(errMsg);
            return false;
        }
        if (TimeUtil.currentTimeMillis() > beginTime + timeout) {
            errMsg = "timeout while waiting for unfinished distributed transactions.";
            logger.info(errMsg);
            return false;
        }
    }
    logger.info("all sessions of distributed transaction  are paused.");
    return true;
}
 
开发者ID:actiontech,项目名称:dble,代码行数:27,代码来源:ShowBinlogStatus.java

示例15: contendedLock

import java.util.concurrent.locks.LockSupport; //导入依赖的package包/类
/**
 * Possibly blocks awaiting root lock.
 */
private final void contendedLock() {
    boolean waiting = false;
    for (int s;;) {
        if (((s = lockState) & ~WAITER) == 0) {
            if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) {
                if (waiting)
                    waiter = null;
                return;
            }
        }
        else if ((s & WAITER) == 0) {
            if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) {
                waiting = true;
                waiter = Thread.currentThread();
            }
        }
        else if (waiting)
            LockSupport.park(this);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:24,代码来源:ConcurrentHashMap.java


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