本文整理汇总了Java中java.util.concurrent.Semaphore.acquire方法的典型用法代码示例。如果您正苦于以下问题:Java Semaphore.acquire方法的具体用法?Java Semaphore.acquire怎么用?Java Semaphore.acquire使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.Semaphore
的用法示例。
在下文中一共展示了Semaphore.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: main
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public static void main(final String[] args) throws InterruptedException, ExecutionException {
final Semaphore s = new Semaphore(0);
connect()
.whenComplete((client, e) -> {
// called when the connect operation finished ... either way
if (e == null) {
System.out.println("Connected");
} else {
System.err.println("Failed to connect");
e.printStackTrace();
}
})
.thenCompose(OpcUaClient::disconnect)
.thenRun(s::release); // wake up s.acquire() below
System.out.println("Wait for completion");
s.acquire(); // what could could wrong?
System.out.println("Bye bye");
}
示例2: readEventsForFilesInDir
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
private void readEventsForFilesInDir(File dir, ReliableEventReader reader,
Collection<String> actual, Semaphore semaphore1,
Semaphore semaphore2) throws IOException {
List<Event> events;
boolean executed = false;
for (int i = 0; i < listFiles(dir).size(); i++) {
events = reader.readEvents(10);
for (Event e : events) {
actual.add(new String(e.getBody()));
}
reader.commit();
try {
if (!executed) {
executed = true;
if (semaphore1 != null) {
semaphore1.release();
}
if (semaphore2 != null) {
semaphore2.acquire();
}
}
} catch (Exception ex) {
throw new IOException(ex);
}
}
}
示例3: getAndCreateSemaphore
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* This Method will fetch an existing Semaphore out of the internal Mapping, identified by the UUID
*
* If the Semaphore does not exist, it will create on.
*
* @param uuid the Identifier of the Semaphore
* @return the identified Semaphore
*/
private Semaphore getAndCreateSemaphore(UUID uuid) {
Semaphore semaphore;
synchronized (semaphoreMap) {
semaphoreMap.computeIfAbsent(uuid, key -> new Semaphore(1));
}
semaphore = getSemaphore(uuid);
try {
semaphore.acquire();
} catch (InterruptedException e) {
logging.catching(e);
}
return semaphore;
}
示例4: testSubmitJobEventListenersEchoStderrWhenExecutorEchoesStderr
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testSubmitJobEventListenersEchoStderrWhenExecutorEchoesStderr() throws InterruptedException {
final Subject<byte[]> stderr = ReplaySubject.create();
final byte[] stderrBytes = generateRandomBytes();
stderr.onNext(stderrBytes);
final JobExecutor jobExecutor = MockJobExecutor.thatUses(Observable.never(), stderr);
final JobManager jobManager = createManagerWith(jobExecutor);
final Semaphore s = new Semaphore(1);
s.acquire();
final JobEventListeners listeners = JobEventListeners.createStderrListener(new Observer<byte[]>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {}
@Override
public void onNext(@NonNull byte[] bytes) {
assertThat(bytes).isEqualTo(stderrBytes);
s.release();
}
@Override
public void onError(@NonNull Throwable throwable) {
fail("Error from observable");
s.release();
}
@Override
public void onComplete() {}
});
jobManager.submit(STANDARD_VALID_REQUEST, listeners);
if (!s.tryAcquire(1, SECONDS)) {
fail("Timed out before any bytes received");
}
}
示例5: init
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* 初始化
* @param threadCount 线程数量
*/
private void init(int threadCount) {
mThread = new Thread(){
@Override
public void run() {
Looper.prepare();
mPoolThreadHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
mThreadPool.execute(taskQueue.removeFirst());
try {
taskSemaphore.acquire();
} catch (InterruptedException e) {
}
}
};
//释放信号量
semaphore.release();
Looper.loop();
}
};
mThread.start();
mLruCache = new LruCache<String,Bitmap>(getCacheMenmory()){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight();
}
};
mThreadPool = Executors.newFixedThreadPool(threadCount);
taskQueue = new LinkedList<>();
taskSemaphore = new Semaphore(threadCount);
}
示例6: test2
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void test2() throws Exception {
String expected = new String(getBytes("test.result.xml"), CHARSET);
Semaphore semaphore = new Semaphore(100, true);
for (int i = 0; i < 100; i++) {
semaphore.acquire();
new MultithreadingTest(i, semaphore, expected).start();
}
semaphore.acquire(100);
}
示例7: play
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* Plays given sequence direct from the console. For testing only.
* Blocks thread while playing.
*
* @param sequence The sequence to play
*/
public synchronized static void play(Sequence sequence) {
try {
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
Synthesizer synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
// Specify the sequence to play, and the tempo to play it at
sequencer.setSequence(sequence);
sequencer.setTempoInBPM(128);
// Use Semaphore to block thread while playing
Semaphore s = new Semaphore(0);
// Let us know when it is done playing
sequencer.addMetaEventListener(m -> {
// A message of this type is automatically sent
// when we reach the end of the track
if (m.getType() == END_OF_TRACK) {
//avoid cut off ending
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
sequencer.stop();
sequencer.close();
synthesizer.close();
s.release();
}
});
// And start playing now.
sequencer.start();
// Block thread while playing
s.acquire();
} catch (MidiUnavailableException | InvalidMidiDataException | InterruptedException e) {
e.printStackTrace();
}
}
示例8: testStartWithCallback
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testStartWithCallback() throws Exception {
final Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
// Seed response from the file.
ResponseHelper.seedResponse("/responses/simple_start_response.json");
// Expected request params.
final HashMap<String, Object> expectedRequestParams = CollectionUtil.newHashMap(
"city", "(detect)",
"country", "(detect)",
"location", "(detect)",
"region", "(detect)",
"locale", "en_US"
);
// Validate request.
RequestHelper.addRequestHandler(new RequestHelper.RequestHandler() {
@Override
public void onRequest(String httpMethod, String apiMethod, Map<String, Object> params) {
assertEquals(Constants.Methods.START, apiMethod);
assertTrue(params.keySet().containsAll(expectedRequestParams.keySet()));
assertTrue(params.values().containsAll(expectedRequestParams.values()));
}
});
Leanplum.start(mContext, new StartCallback() {
@Override
public void onResponse(boolean success) {
assertTrue(success);
semaphore.release();
}
});
assertTrue(Leanplum.hasStarted());
}
示例9: test4
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* Test 4: Multithreading-Test.
*
* @throws Exception
*/
@Test
public void test4() throws Exception {
Semaphore semaphore = new Semaphore(100, true);
for (int i = 0; i < 100; i++) {
semaphore.acquire();
new MultithreadingTest(i, semaphore).start();
}
semaphore.acquire(100);
}
示例10: acquireGroupSendPermission
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
private void acquireGroupSendPermission(boolean ordered) {
if (this.disconnected) {
throw new org.apache.geode.distributed.DistributedSystemDisconnectedException(
LocalizedStrings.DirectChannel_DIRECT_CHANNEL_HAS_BEEN_STOPPED.toLocalizedString());
}
// @todo darrel: add some stats
final Semaphore s = getGroupSem(ordered);
for (;;) {
this.conduit.getCancelCriterion().checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
s.acquire();
break;
} catch (InterruptedException ex) {
interrupted = true;
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
} // for
if (this.disconnected) {
s.release();
throw new DistributedSystemDisconnectedException(
LocalizedStrings.DirectChannel_COMMUNICATIONS_DISCONNECTED.toLocalizedString());
}
}
示例11: testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
@Test
public void testSubmitJobEventListenersEchoStdoutWhenExecutorEchoesStdout() throws InterruptedException {
final Subject<byte[]> stdoutSubject = ReplaySubject.create();
final byte[] expectedStdoutBytes = generateRandomBytes();
stdoutSubject.onNext(expectedStdoutBytes);
final JobExecutor jobExecutor = MockJobExecutor.thatUses(stdoutSubject, Observable.never());
final JobManager jobManager = createManagerWith(jobExecutor);
final Semaphore s = new Semaphore(1);
s.acquire();
final JobEventListeners listeners = JobEventListeners.createStdoutListener(new Observer<byte[]>() {
@Override
public void onSubscribe(@NonNull Disposable disposable) {}
@Override
public void onNext(@NonNull byte[] bytes) {
assertThat(bytes).isEqualTo(expectedStdoutBytes);
s.release();
}
@Override
public void onError(@NonNull Throwable throwable) {
fail("Error from observable");
s.release();
}
@Override
public void onComplete() {}
});
jobManager.submit(STANDARD_VALID_REQUEST, listeners);
if (!s.tryAcquire(1, SECONDS)) {
fail("Timed out before any bytes received");
}
}
示例12: executeSameTimeJob
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* 并行任务处理方式
*/
private boolean executeSameTimeJob(final long groupId, final Queue<JobVo> jobQueue) {
final List<Boolean> result = new ArrayList<Boolean>(0);
final Semaphore semaphore = new Semaphore(jobQueue.size());
ExecutorService exec = Executors.newCachedThreadPool();
for (final JobVo jobVo : jobQueue) {
Runnable task = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
result.add(doFlowJob(jobVo, groupId));
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
}
};
exec.submit(task);
}
exec.shutdown();
while (true) {
if (exec.isTerminated()) {
logger.info("[opencron]SameTimeJob,All doned!");
return !result.contains(false);
}
}
}
示例13: OutputReader
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public OutputReader() {
try {
outputSem = new Semaphore(1);
outputSem.acquire();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
示例14: acquire
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
public static void acquire(Semaphore semaphore) {
try {
semaphore.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
示例15: invoke
import java.util.concurrent.Semaphore; //导入方法依赖的package包/类
/**
* Processes a method invocation on a proxy instance and returns
* the result. This method will be invoked on an invocation handler
* when a method is invoked on a proxy instance that it is
* associated with.
*
* @param proxy the proxy instance that the method was invoked on
* @param method the {@code Method} instance corresponding to
* the interface method invoked on the proxy instance. The declaring
* class of the {@code Method} object will be the interface that
* the method was declared in, which may be a superinterface of the
* proxy interface that the proxy class inherits the method through.
* @param args an array of objects containing the values of the
* arguments passed in the method invocation on the proxy instance,
* or {@code null} if interface method takes no arguments.
* Arguments of primitive types are wrapped in instances of the
* appropriate primitive wrapper class, such as
* {@code java.lang.Integer} or {@code java.lang.Boolean}.
* @return the value to return from the method invocation on the
* proxy instance. If the declared return type of the interface
* method is a primitive type, then the value returned by
* this method must be an instance of the corresponding primitive
* wrapper class; otherwise, it must be a type assignable to the
* declared return type. If the value returned by this method is
* {@code null} and the interface method's return type is
* primitive, then a {@code NullPointerException} will be
* thrown by the method invocation on the proxy instance. If the
* value returned by this method is otherwise not compatible with
* the interface method's declared return type as described above,
* a {@code ClassCastException} will be thrown by the method
* invocation on the proxy instance.
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
RemoteAccessCommunicationRequest request = new RemoteAccessCommunicationRequest(method.getName(), clazz, uuid, args);
Semaphore semaphore = remoteAccessBlockRegistration.await(request);
sender.objectToServer(request);
semaphore.acquire();
RemoteAccessCommunicationResponse response = remoteAccessBlockRegistration.getResponse(uuid);
remoteAccessBlockRegistration.clearResult(uuid);
remoteAccessBlockRegistration.clearSemaphore(uuid);
semaphore.release();
if(response.getThrownThrowable() != null) {
testForThrow(clazz, response.getThrownThrowable());
}
return response.getResult();
}