同步代码块

什么是同步代码块

使用synchronize关键字加上锁对象来定义一段代码,这就叫同步代码块。

什么时候使用同步代码块

当多线程并发,有多段代码同时执行,如果希望一段代码在执行过程中多CPU不要切换到其他线程工作,这时就需要用到同步代码块。

示例

public class Demo1_Synchronized {

    public static void main(String[] args) {
        Printer p = new Printer();
        new Thread(){
            public void run(){
                while(true){
                    p.print1();
                }
            }
        }.start();

        new Thread(){
            public void run(){
                while(true){
                    p.print2();
                }
            }
        }.start();
    }

}

class Printer{
    Demo d = new Demo();
    public void print1(){
        synchronized(Printer.class) {                 // 同步代码块,锁机制,锁对象可以是任意的,但两条线程的锁对象要相同,括号中也可以传d
            System.out.print("同");
            System.out.print("步");
            System.out.print("代");
            System.out.print("码");
            System.out.print("块");
            System.out.println();
        }
    }

    public void print2(){
        synchronized(Printer.class){                         // 锁对象不能用匿名对象,因为匿名对象不是同一个对象
            System.out.print("s");
            System.out.print("y");
            System.out.print("n");
            System.out.print("c");
            System.out.print("h");
            System.out.print("r");
            System.out.print("o");
            System.out.print("n");
            System.out.print("i");
            System.out.print("z");
            System.out.print("e");
            System.out.print("d");
            System.out.println();
        }
    }
}

class Demo{}

同步方法

在方法上加synchronize关键字,就是同步方法。
非静态同步方法的锁对象是this
静态方法的锁对象是该类的字节码对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值