synchronized
public synchronized void method(){}
ReentrantLock
private final ReentrantLock lock = new ReentrantLock();
public void method(){
lock.lock();
try{
...
}finally{
lock.unlock();
}
}
CountDownLatch
private final CountDownLatch latch = new CountDownLatch(3);
public void method() throws InterruptedException{
for(String str:list){
new Thread(()->{
//doSomething
//计数器-1
latch.countDown();
}).start();
}
//主线程阻塞
latch.await();
}
Semaphore
private final Semaphore semaphore = new Semaphore(3);
public void method(){
semaphore.acquire();
try{
//doSomething
}finally{
semaphore.release();
}
}
评论区