A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© ft352177 中级黑马   /  2016-5-23 01:11  /  561 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.heima.syn;

public class Demo1_Synchronized {

        /**
         * @param args
         * 同步代码块
         */
        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 d = new Demo();
        public void print1() {
                //synchronized(new Demo()) {                                                        //同步代码块,锁机制,锁对象可以是任意的
                synchronized(d) {
                        System.out.print("黑");
                        System.out.print("马");
                        System.out.print("程");
                        System.out.print("序");
                        System.out.print("员");
                        System.out.print("\r\n");
                }
        }
       
        public void print2() {
                //synchronized(new Demo()) {                                                        //锁对象不能用匿名对象,因为匿名对象不是同一个对象
                synchronized(d) {               
                        System.out.print("传");
                        System.out.print("智");
                        System.out.print("播");
                        System.out.print("客");
                        System.out.print("\r\n");
                }
        }
}

class Demo{}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马