通过内部类来分析synchronized同步的使用、同步对象、同步方法、同步静态资源 public class TraditionalThreadSynchronized {/** *title:main *@param args */public static void main(String[] args) {new TraditionalThreadS
public class TraditionalThreadSynchronized {
/**
*title:main
*@param args
*/
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}
public void init(){
final OutputChar outputChar = new OutputChar();
/**第一个线程*/
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {e.printStackTrace();}
outputChar.printChar("maoyuanming");
}
}
}).start();
/**第二个线程*/
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(500);
} catch (InterruptedException e) {e.printStackTrace();}
outputChar.printChar("duanxueqiang");
}
}
}).start();
}
/**内部类,用来打印字符串*/
static class OutputChar{
public void printChar(String str){
synchronized (OutputChar.class) {
int len = str.length();
for(int i=0;i < len;i++){
System.out.print(str.charAt(i));
}
System.out.println();
}
}
public synchronized void printChar1(String str){
int len = str.length();
for(int i=0;i < len;i++){
System.out.print(str.charAt(i));
}
System.out.println();
}
}
}
//==============================小总结==================
synchronized同步实际上同步的是一个对象,同步的共享资源就是一个对象。
同步普通方法锁的是对象,而同步静态方法,虽然锁的是类,但对于类在内存中就是一份字节码,也相当于是一个对象
