public class TestThread {
public static void main( String[] args ) {
TestMath1 tm = new TestMath1();
new Thread ( tm , "TestMath1" ).start();
new Thread ( tm , "TestMath2" ).start();
// TestMath2 tm2 = new TestMath2();
// new Thread ( tm2 , "TestMath2" ).start();
}
}
class TestMath1 implements Runnable {
public void run() {
new Maths().execute( this );
}
}
class TestMath2 implements Runnable {
public void run() {
new Maths().execute( this );
}
}
class Maths {
/*
static Object o = new Object();
public void execute() {
synchronized( o ) {//同步锁,用于锁住当前类实例,知道执行完毕解锁
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
}
public synchronized void execute() {
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
public void execute() {
synchronized( this ) {
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
}*/
public void execute( Object o ) {
synchronized( o ) {
int i = 0;
while ( i < 20 ) {
System.out.println( Thread.currentThread().getName()+":"+ i );
i++;
}
}
}
}