锁 synchronized/lock
synchronized/lock对比
synchronized方法和synchronized块
同步方法: public synchronized void method(int args){}
synchronized方法控制对“对象”的访问﹐每个对象对应一把锁﹐每个synchronized方法都必须获得调用该方法的对象的锁才能执行﹐否则线程会阻塞,方法一旦执行﹐就独占该锁,直到该方法返回才释放锁﹐后面被阻塞的线程才能获得这个锁,继续执行
缺陷:若将一个大的方法申明为synchronized将会影响效率
synchronized 修饰词
package Thread.Demo09;
/** synchronized 修饰词
* 只能1个线程对对象操作
* @author liu
*/
public class UnSafeBuyTick {
public static void main(String[] args) {
BuyTick buyTick = new BuyTick();
Thread thread1 = new Thread(buyTick,"A");
Thread thread2 = new Thread(buyTick,"B");
Thread thread3 = new Thread(buyTick,"C");
thread1.start();
thread2.start();
thread3.start();
}
}
class BuyTick implements Runnable {
private int tick = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
while(flag){
buy();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void buy() {
if (tick <= 0) {
flag=false;
return ;
}
System.out.println(Thread.currentThread().getName() + "买到" + tick--);
}
}
synchronized(){} 同步锁方法块
package Thread.Demo09;
import java.util.ArrayList;
import java.util.List;
/**synchronized(){} 同步锁方法块
* @author liu
*/
public class UnSafeThread02 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(() -> {
synchronized (list){ list.add(Thread.currentThread().getName());
}}).start();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
lock
package Thread.Demo09;
import java.util.concurrent.locks.ReentrantLock;
/**LOCK锁
* @author liu
*/
public class Lock {
public static void main(String[] args) {
buyTick1 buyTick = new buyTick1();
Thread thread1 = new Thread(buyTick, "A");
Thread thread2 = new Thread(buyTick, "B");
Thread thread3 = new Thread(buyTick, "C");
thread1.start();
thread2.start();
thread3.start();
}
}
class buyTick1 implements Runnable {
private int tick = 10;
//定义一个lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
lock.lock();
if (tick > 0) {
System.out.println(Thread.currentThread().getName() + "买到" + tick--);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
} finally {
lock.unlock();
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现