并不是只要加了锁就是安全(互斥)的

来源:互联网 发布:mdf ldf 还原数据库 编辑:程序博客网 时间:2024/04/30 15:03
public class ThreadSafeDemo {public static void main(String[] args) {// TODO Auto-generated method stubnew ThreadSafeDemo().init(); }public void init(){ final Outputer op = new Outputer();new Thread(new Runnable(){@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){op.output1("yinhang");}}}).start();new Thread(new Runnable(){public void run(){while(true){op.output2("zhuanzhang");}}}).start();}static class Outputer{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();}public void output2(String name){synchronized(this){ int len = name.length();for(int i=0;i<len;i++){System.out.print(name.charAt(i)); }System.out.println();}}public static void output3(String name){synchronized(Outputer.class){ int len = name.length();for(int i=0;i<len;i++){System.out.print(name.charAt(i)); }System.out.println();}}public static synchronized void output4(String name){int len = name.length();for(int i=0;i<len;i++){System.out.print(name.charAt(i)); }System.out.println();}}}


其中,output1()和output2()是线程安全的;

output3()和output4()是线程安全的;


Note:并不是只要加了锁就是安全(互斥)的!! 只有满足加的那把锁(latch,门闩)一定是同一个对象时才是线程安全的!!

用synchronized修饰非static方法等同于synchronized(this){};

用synchronized修饰static方法等同于synchronized(xxx.class);

因为static会编译成字节码,xxx.class也是字节码,为同一个对象!





0 0
原创粉丝点击