同步代码块 synchronized

  当多线程并发时,  有多段代码同时执行时,我们希望 某一段代码执行的过程中,CPU不要切换到其他线程工作

  这时就需要同步.,如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码

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

      锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象

        因为匿名对象  就不是同一把锁了

public class demon_syn {

    public static void main(String[] args) {
        final 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 d1 = new demo();
    public  void print1(){
        synchronized (d1) {         //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象
            System.out.print("黑");
            System.out.print("马");
            System.out.print("程");
            System.out.print("序");
            System.out.print("员");
            System.out.print("
");
        }
        
        
    }
    public  void print2(){
        synchronized (d1) {
            System.out.print("传");
            System.out.print("智");
            System.out.print("播");
            System.out.print("客");
            System.out.print("
");
        }
        
    }
}

class demo{
    
}
竹杖芒鞋轻胜马,一蓑烟雨任平生。 回首向来萧瑟处,也无风雨也无晴。
原文地址:https://www.cnblogs.com/yaobiluo/p/11347296.html