public static void main(String[] args) {
final Printer p1 = new Printer();
final Printer p2 = new Printer();
new Thread("线程1:"){
public void run() {
for (int i = 1; i <= 3; i++)
try{
p1.print();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
new Thread("线程2:"){
public void run() {
for (int i = 1; i <= 3; i++)
try{
p2.print();
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
}
class Printer{
public synchronized void print() throws Exception {
for (int i = 1; i <= 3; i++)
System.out.println(Thread.currentThread().getName()+ i);
System.out.println();
}
}