Synchronized

来源:互联网 发布:jre windows x64.exe 编辑:程序博客网 时间:2024/04/28 22:12
package com.Thread;/* * synchronized(Object) * 同步时object对象必须是同一个 */public class TraditionalSynchronized {    public static void main(String[] args){        new TraditionalSynchronized().init();    }    public void init(){        final OutPuter outPuter = new OutPuter();   //注意静态方法里面(比如main)不能创建内部类,解决办法:实例化外部类对象,对象调用方法        new Thread(new Runnable(){            public void run(){                while(true){                    outPuter.output("zengjinhuaihahahahahahahahhahahaahhahahah");                }            }        }).start();             new Thread(new Runnable(){            public void run(){                while(true){                    OutPuter.output2("zhourui");                }            }        }).start();         }    static class OutPuter{        public  void output(String name){            int len = name.length();       //       不知道能不能同步            synchronized(OutPuter.class){        //this和output1同步,OutPuter.class和output2同步 (静态方法,以字节码文件作为句柄,字节码文件是一份)                for(int i=0;i<len;i++){                    System.out.print(name.charAt(i));                }                System.out.println();                try {                    Thread.currentThread().sleep(500);                } catch (InterruptedException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }/*      public synchronized void output1(String name){            int len = name.length();            for(int i=0;i<len;i++){                System.out.print(name.charAt(i));            }            System.out.println();            try {                Thread.currentThread().sleep(500);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }*/              static synchronized void output2(String name){            int len = name.length();            for(int i=0;i<len;i++){                System.out.print(name.charAt(i));            }            System.out.println();            try {                Thread.currentThread().sleep(500);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}
0 0
原创粉丝点击