java syncr_JAVA基础—Synchronized线程同步机制

Synchronize的使用场景

Synchronize可以使用在一下三种场景,对应不同的锁对象

场景

synchronized代码块

synchronized方法

synchronized静态方法

锁对象

任意对象

this 对象

该类的字节码对象 *.class

没有同步代码实例

public class SyncSample {

public static void main(String[] args) {

Couplet couplet = new Couplet();

for (int i = 1; i < 1000; i++)

new Thread() {

public void run() {

int r = new Random().nextInt(2);

if (r % 2 == 0){

couplet.first();

}else {

couplet.second();

}

}

}.start();

}

}

class Couplet {

public void first() {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

public void second() {

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魉");

System.out.println();

}

}

运行结果

...

魑魅魍魉

琴瑟琵琶

琴瑟琴瑟琵琶

魍魉

琴瑟琵琶

琴瑟琵魅魍魉

魑魅瑟琵琶

1. synchronized代码块 解决

class Couplet {

//创建锁对象 可以是任意对象 也可用当前对象this

Object lock = new Object();

public void first() {

//代码块 需要有锁对象

synchronized (lock) {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

}

public void second() {

//代码块 需要有锁对象

synchronized (lock) {

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魉");

System.out.println();

}

}

}

运行结果

琴瑟琵琶

魑魅魍魉

琴瑟琵琶

魑魅魍魉

2. synchronized方法 同步方法解决

class Couplet {

//同步方法 this当前对象就是锁对象

public synchronized void first() {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

//代码块与同步方法 同步时 使用this当前对象

public void second() {

synchronized (this){

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魉");

System.out.println();

}

}

}

运行结果

琴瑟琵琶

魑魅魍魉

琴瑟琵琶

魑魅魍魉

3. synchronized静态方法

class Couplet {

//静态同步方法 当前对象.class 的字节码对象就是锁对象

public synchronized static void first() {

System.out.printf("琴");

System.out.printf("瑟");

System.out.printf("琵");

System.out.printf("琶");

System.out.println();

}

//代码块与静态方法同步时 使用当前字节码锁对象

public void second() {

synchronized (Couplet.class){

System.out.printf("魑");

System.out.printf("魅");

System.out.printf("魍");

System.out.printf("魉");

System.out.println();

}

}

}

运行结果

琴瑟琵琶

魑魅魍魉

琴瑟琵琶

魑魅魍魉

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值