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


Java Semaphore类代码示例

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


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

示例1: loop

import java.util.concurrent.Semaphore; //导入依赖的package包/类
final int loop(int n) {
    final Semaphore sem = this.sem;
    int sum = 0;
    int x = 0;
    while (n-- > 0) {
        sem.acquireUninterruptibly();
        try {
            x = setValue(LoopHelpers.compute1(getValue()));
        }
        finally {
            sem.release();
        }
        sum += LoopHelpers.compute2(x);
    }
    return sum;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:CheckedLockLoops.java

示例2: beforeSend

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Override
protected synchronized void beforeSend(final Object object) {
	NetCom2Utils.assertNotNull(object);
	if (object.getClass().equals(Acknowledge.class)) {
		logging.trace("[TCP] No need to setup an synchronization mechanism an Acknowledge!");
		return;
	}
	logging.trace("[TCP] Locking access to send ..");
	communicationLock.lock();
	logging.debug("[TCP] Preparing send of " + object + " at Thread " + Thread.currentThread());
	final Semaphore semaphore = new Semaphore(1);
	logging.trace("[TCP] ClientMapping synchronization mechanism ..");
	synchronized (mapping) {
		mapping.put(object.getClass(), semaphore);
	}
	logging.trace("[TCP] Setting up Callback ..");
	receivingService.addReceivingCallback(new TCPAckCallback(object.getClass()));
}
 
开发者ID:ThorbenKuck,项目名称:NetCom2,代码行数:19,代码来源:TCPDefaultConnection.java

示例3: testRemoveListener

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Test
public void testRemoveListener()
    throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  final Semaphore semaphore = new Semaphore(0);
  ValueEventListener listener = ref.limitToLast(5)
      .addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
          semaphore.release();
        }

        @Override
        public void onCancelled(DatabaseError error) {
        }
      });

  ref.setValueAsync(MapBuilder.of("a", 5, "b", 6));
  TestHelpers.waitFor(semaphore, 1);
  ref.limitToLast(5).removeEventListener(listener);
  new WriteFuture(ref, MapBuilder.of("a", 6, "b", 5)).timedGet();
  TestHelpers.waitForQueue(ref);

  assertEquals(0, semaphore.availablePermits());
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:27,代码来源:QueryTestIT.java

示例4: testSetPriority

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Test
public void testSetPriority() throws InterruptedException {
  final DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);

  ref.setValueAsync("hello!");
  final Semaphore semaphore = new Semaphore(0);
  ref.setPriority(10, new DatabaseReference.CompletionListener() {
    @Override
    public void onComplete(DatabaseError error, DatabaseReference callbackRef) {
      assertEquals(ref, callbackRef);
      assertNull(error);
      semaphore.release(1);
    }
  });

  assertTrue(semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:18,代码来源:DataTestIT.java

示例5: testUpdateAfterSetLeafNodeWorks

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Test
public void testUpdateAfterSetLeafNodeWorks() throws InterruptedException {
  DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
  final Semaphore semaphore = new Semaphore(0);
  final Map<String, Object> expected = new MapBuilder().put("a", 1L).put("b", 2L).build();

  ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
      if (DeepEquals.deepEquals(snapshot.getValue(), expected)) {
        semaphore.release();
      }
    }

    @Override
    public void onCancelled(DatabaseError error) {
    }
  });
  ref.setValueAsync(42);
  ref.updateChildrenAsync(expected);

  TestHelpers.waitFor(semaphore);
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:24,代码来源:DataTestIT.java

示例6: test2

import java.util.concurrent.Semaphore; //导入依赖的package包/类
/**
 * @throws Exception
 */
@Test
public void test2() throws Exception {
	Semaphore semaphore = new Semaphore(10, true);
	for (int i = 0; i < MAX_THREAD_COUNT; i++) {
		new MultithreadingTest(i, semaphore, this).start();
		if (i > 0 && i % 100 == 0) {
			synchronized (this) {
				while (counter != i) {
					wait();
				}
			}
		}
	}
	synchronized (this) {
		while (counter != MAX_THREAD_COUNT) {
			wait();
		}
		System.out.println("counter: " + counter);
	}
}
 
开发者ID:dvbern,项目名称:doctemplate,代码行数:24,代码来源:ConvertOdtToPdfTest_OO.java

示例7: getSnap

import java.util.concurrent.Semaphore; //导入依赖的package包/类
public static DataSnapshot getSnap(Query ref) throws InterruptedException {

    final Semaphore semaphore = new Semaphore(0);

    // Hack to get around final reference issue
    final List<DataSnapshot> snapshotList = new ArrayList<>(1);

    ref.addListenerForSingleValueEvent(
        new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot snapshot) {
            snapshotList.add(snapshot);
            semaphore.release(1);
          }

          @Override
          public void onCancelled(DatabaseError error) {
            semaphore.release(1);
          }
        });

    semaphore.tryAcquire(1, TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    return snapshotList.get(0);
  }
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:25,代码来源:TestHelpers.java

示例8: release

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@APILevel
void release(RemoteAccessCommunicationResponse response) {
	synchronized (responseMap) {
		responseMap.put(response.getUuid(), response);
	}
	Semaphore semaphore = getSemaphore(response.getUuid());

	if(semaphore == null) {
		return;
	}

	semaphore.release();
}
 
开发者ID:ThorbenKuck,项目名称:NetCom2,代码行数:14,代码来源:RemoteAccessBlockRegistration.java

示例9: open

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Override
public Point open(SurfaceTexture surface) {
    try {
        if(!extractMedia()){
            return new Point(0,0);
        }
        mFrameSem=new Semaphore(0);
        mDecodeSem=new Semaphore(1);
        videoProvideEndFlag=false;
        isUserWantToStop=false;
        mAudioEncodeTrack=mStore.addTrack(mExtractor.getTrackFormat(mAudioDecodeTrack));
        MediaFormat format=mExtractor.getTrackFormat(mVideoDecodeTrack);
        mVideoDecoder = MediaCodec.createDecoderByType(format.getString(MediaFormat.KEY_MIME));
        mVideoDecoder.configure(format,new Surface(surface),null,0);
        mVideoDecoder.start();
        startDecodeThread();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return mVideoSize;
}
 
开发者ID:aiyaapp,项目名称:AAVT,代码行数:22,代码来源:Mp4Provider.java

示例10: testRangeMergeUpdate

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Test
public void testRangeMergeUpdate() throws InterruptedException {
  final Repo repo = newRepo();
  final List<DataSnapshot> events = new ArrayList<>();
  QuerySpec spec = new QuerySpec(new Path("/rangeMerge"), QueryParams.DEFAULT_PARAMS);
  addCallback(repo, new ValueEventRegistration(repo, newValueEventListener(events), spec));

  final Semaphore semaphore = new Semaphore(0);
  final RangeMerge merge = new RangeMerge(ImmutableList.of("p1"),
      ImmutableList.of("p5"), ImmutableMap.of("p2", "v2", "p3", "v3"));
  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.onRangeMergeUpdate(
          ImmutableList.of("rangeMerge"), ImmutableList.of(merge), null);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertEquals(1, events.size());
  assertNotNull(events.get(0));
  assertEquals(ImmutableMap.of("p2", "v2", "p3", "v3"), events.get(0).getValue());
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:24,代码来源:RepoTest.java

示例11: testSetValue

import java.util.concurrent.Semaphore; //导入依赖的package包/类
@Test
public void testSetValue() throws InterruptedException {
  final Repo repo = newRepo();
  final List<DataSnapshot> events = new ArrayList<>();
  final Path path = new Path("/foo");
  QuerySpec spec = new QuerySpec(path, QueryParams.DEFAULT_PARAMS);
  addCallback(repo, new ValueEventRegistration(repo, newValueEventListener(events), spec));

  final Semaphore semaphore = new Semaphore(0);
  repo.scheduleNow(new Runnable() {
    @Override
    public void run() {
      repo.setValue(path, NodeUtilities.NodeFromJSON("setValue"), null);
      semaphore.release();
    }
  });
  waitFor(semaphore);
  assertEquals(1, events.size());
  assertNotNull(events.get(0));
  assertEquals("setValue", events.get(0).getValue(String.class));
}
 
开发者ID:firebase,项目名称:firebase-admin-java,代码行数:22,代码来源:RepoTest.java

示例12: processLogic

import java.util.concurrent.Semaphore; //导入依赖的package包/类
private void processLogic(Bundle savedInstanceState) {
    this.mSaveImgDir = (File) getIntent().getSerializableExtra(EXTRA_SAVE_IMG_DIR);
    if (this.mSaveImgDir == null) {
        this.mDownloadIv.setVisibility(4);
    }
    this.mPreviewImages = getIntent().getStringArrayListExtra(EXTRA_PREVIEW_IMAGES);
    this.mIsSinglePreview = getIntent().getBooleanExtra(EXTRA_IS_SINGLE_PREVIEW, false);
    if (this.mIsSinglePreview) {
        this.mPreviewImages = new ArrayList();
        this.mPreviewImages.add(getIntent().getStringExtra(EXTRA_PHOTO_PATH));
    }
    int currentPosition = getIntent().getIntExtra(EXTRA_CURRENT_POSITION, 0);
    this.mContentHvp.setAdapter(new ImagePageAdapter());
    this.mContentHvp.setCurrentItem(currentPosition);
    renderTitleTv();
    this.mSemaphore = new Semaphore(1);
    this.mTitleRl.postDelayed(new Runnable() {
        public void run() {
            MQPhotoPreviewActivity.this.hiddenTitlebar();
        }
    }, 2000);
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:23,代码来源:MQPhotoPreviewActivity.java

示例13: MiniConnectionPoolManager

import java.util.concurrent.Semaphore; //导入依赖的package包/类
/**
 * Constructs a MiniConnectionPoolManager object.
 *
 * @param dataSource the data source for the connections.
 * @param maxConnections the maximum number of connections.
 * @param timeout the maximum time in seconds to wait for a free connection.
 */
public MiniConnectionPoolManager(ConnectionPoolDataSource dataSource, int maxConnections,
    int timeout) {
    this.dataSource = dataSource;
    this.maxConnections = maxConnections;
    this.timeoutMs = timeout * 1000L;
    try {
        logWriter = dataSource.getLogWriter();
    } catch (SQLException e) {
    }
    if (maxConnections < 1) {
        throw new IllegalArgumentException("Invalid maxConnections value.");
    }
    semaphore = new Semaphore(maxConnections, true);
    recycledConnections = new LinkedList<PooledConnection>();
    poolConnectionEventListener = new PoolConnectionEventListener();
}
 
开发者ID:stechy1,项目名称:drd,代码行数:24,代码来源:MiniConnectionPoolManager.java

示例14: SharedByteArray

import java.util.concurrent.Semaphore; //导入依赖的package包/类
public SharedByteArray(
    MemoryTrimmableRegistry memoryTrimmableRegistry,
    PoolParams params) {
  Preconditions.checkNotNull(memoryTrimmableRegistry);
  Preconditions.checkArgument(params.minBucketSize > 0);
  Preconditions.checkArgument(params.maxBucketSize >= params.minBucketSize);

  mMaxByteArraySize = params.maxBucketSize;
  mMinByteArraySize = params.minBucketSize;
  mByteArraySoftRef = new OOMSoftReference<byte[]>();
  mSemaphore = new Semaphore(1);
  mResourceReleaser = new ResourceReleaser<byte[]>() {
    @Override
    public void release(byte[] unused) {
      mSemaphore.release();
    }
  };

  memoryTrimmableRegistry.registerMemoryTrimmable(this);
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:21,代码来源:SharedByteArray.java

示例15: testSearchScopesNotifiedAboutChangesInEDT

import java.util.concurrent.Semaphore; //导入依赖的package包/类
public void testSearchScopesNotifiedAboutChangesInEDT()
        throws InterruptedException {
    CustomSearchScope css = new CustomSearchScope(true, 1);
    SearchScopeList ssl = new SearchScopeList(css);
    final Semaphore s = new Semaphore(0);
    final AtomicBoolean notifiedInEDT = new AtomicBoolean(false);
    ssl.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            notifiedInEDT.set(EventQueue.isDispatchThread());
            s.release();
        }
    });
    css.fireChangeEvent();
    boolean acqrd = s.tryAcquire(10, TimeUnit.SECONDS);
    assertTrue("Should be notified in EDT", acqrd && notifiedInEDT.get());
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:18,代码来源:SearchScopeListTest.java


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