public class TraditionalSychronized {
/**
* @param args
*/
public static void main(String[] args) {
new TraditionalSychronized().init();
}
public void init() {
final Printer printer = new Printer();
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
printer.print("youyang");
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
printer.print("yusiyi");
}
}
}.start();
}
static class Printer {
public void print(String string) {
//当线程运行到这里时,就会检查this的锁是否还在,在就获取锁,运行里面的代码
//如果锁不在,就等待,直到得到锁
synchronized (this) {
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
}
System.out.println();
}
}
//synchronized方法中用到的互斥对象也是this,所以print方法和print2方法能同步
public synchronized void print2(String string) {
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
}
System.out.println();
}
//static synchronized方法中用到的互斥对象就是类本身,即Printer.class,所以不能和print方法同步
public static synchronized void print3(String string) {
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
}
System.out.println();
}
}
}