锁 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();
            }
        }
    }
}
posted @   小幼虫虫  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示