使用synchronized实现同步

我们先来看一段代码:

class TicketThread implements Runnable{
   
    private int ticket = 10;
    @Override
    public void run() {
   
        while(this.ticket>0){
   
            try {
   
                Thread.sleep(1000);
            } catch (InterruptedException e) {
   
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"正在为您服务,当前还剩 "+this.ticket--+" 张票");
        }
    }
}

public class TestDemo {
   
    public static void main(String[] args) {
   
        TicketThread ticketThread = new TicketThread();
        Thread thread1 = new Thread(ticketThread,"1号售票员");
        Thread thread2 = new Thread(ticketThread,"2号售票员");
        Thread thread3 = new Thread(ticketThread,"3号售票员");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

结果如下:
在这里插入图片描述
可以看到,当前代码出现了负数票的情况,这是因为不同步而导致的。

我们可以使用synchronized关键字来实现同步,实际上也就是加锁操作,使得同一时刻只能有一个线程获取到锁而进入同步代码块中。

使用synchronized关键字处理有两种模式:同步代码块与同步方法。接下来我们分别看一下这两种方式,就以上面的代码为例:

1.同步代码块:
此时我们只需要锁住卖票的对象就可以了,这样同一时刻只能有一个对象拿到锁并卖票

public void run() {
   
        for(int i = 0;i<10;i++){
   
            synchronized (this){
   
                if(this
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值