多线程(同步方法)学习笔记

使用synchronized关键字修饰一个方法, 该方法中所有的代码都是同步的

        class Printer {
            public static void print1() {
                synchronized(Printer.class){                //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象
                    System.out.print("黑");
                    System.out.print("马");
                    System.out.print("程");
                    System.out.print("序");
                    System.out.print("员");
                    System.out.print("\r\n");
                }
            }
            /*
             * 非静态同步函数的锁是:this
             * 静态的同步函数的锁是:字节码对象
             */
            public static synchronized void print2() {  
                System.out.print("传");
                System.out.print("智");
                System.out.print("播");
                System.out.print("客");
                System.out.print("\r\n");
            }
        }

猜你喜欢

转载自blog.51cto.com/357712148/2156473