public class ThreadSafeDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
new ThreadSafeDemo().init();
}
public void init(){
final Outputer op = new Outputer();
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while(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也是字节码,为同一个对象!