【学习笔记】线程原子性-锁 synchronized的用法,rabbitmq与kafka面试

本文探讨了synchronized修饰方法、类和静态方法在Java并发编程中的应用,通过示例展示了其如何确保线程原子性和防止竞态条件。同时,文章还提及了线程不安全的情况,并提到了面试中可能涉及的RabbitMQ和Kafka相关知识。
摘要由CSDN通过智能技术生成

//两个线程调用了同一个对象

executorService.execute(() ->{

example1.test1(1);

});

executorService.execute(() ->{

example2.test1(2);

});

}

}

返回结果:

test1 j:1 — i:0

test1 j:1 — i:1

test1 j:1 — i:2

test1 j:1 — i:3

test1 j:1 — i:4

test1 j:1 — i:5

test1 j:1 — i:6

test1 j:1 — i:7

test1 j:1 — i:8

test1 j:1 — i:9

test1 j:2 — i:0

test1 j:2 — i:1

test1 j:2 — i:2

test1 j:2 — i:3

test1 j:2 — i:4

test1 j:2 — i:5

test1 j:2 — i:6

test1 j:2 — i:7

test1 j:2 — i:8

test1 j:2 — i:9

线程1和线程2按照各自顺序执行,线程一和线程二都能够按照自己的同步代码走下去,但是不一定能保证线程一执行完之后才到线程二执行,这就要看哪一个线程能够率先抢到资源。

修饰方法

package com.lyy.concurrency.sync;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class SynchronizedExample1 {

//修饰一个方法

public synchronized void test2(int j){

for (int i = 0; i < 10; i++) {

System.out.println(“test2 j:”+j+" — i:"+i);

}

}

public static void main(String[] args) {

SynchronizedExample1 example1 = new SynchronizedExample1();

Syn

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值