package com.heima.Thread;
public class Demo7_synchronized {
/**
* @param args
*/
public static void main(String[] args) {
final Printer p = new Printer(); //
new Thread() {
public void run() {
while(true) {
p.print1();
}
}
}.start();
new Thread() {
public void run() {
while(true) {
p.print2(); // 匿名内部类使用局部变量需要用final修饰
}
}
}.start();
}
}
class Printer {
Demo d = new Demo();
public void print1() {
synchronized (d) {
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println("\r\n");
}
}
public void print2() {
synchronized (d) {
System.out.println("6");
System.out.println("7");
System.out.println("8");
System.out.println("9");
System.out.println("10");
System.out.println("\r\n");
}
}
}
class Demo{}