侧边栏壁纸
博主头像
IT充电站博主等级

看过故人终场戏,淡抹最适宜

  • 累计撰写 48 篇文章
  • 累计创建 13 个标签
  • 累计收到 2 条评论

目 录CONTENT

文章目录

线程同步的4种常用方式

陈汉林
2024-05-24 / 0 评论 / 0 点赞 / 14 阅读 / 1336 字

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();
	}
}

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区