线程t1
正在调用test1()
Test类对象ob的方法。
线程在同步块t2
中调用test1()
Test类对象ob的方法。即使ob 的方法调用在线程的同步块中,
t1
也能够调用ob 的方法。test1()
test1()
t2
代码如下:
class Test {
void test1() {
while(1 == 1) {
System.out.println(Thread.currentThread().getName() + " test1!");
}
}
void test2() {
while(1 == 1) {
System.out.println(Thread.currentThread().getName() + " test2!");
}
}
}
class NewThread1 implements Runnable {
Thread t;
String name;
Test target;
NewThread1(Test ob, String threadname) {
target = ob;
name = threadname;
t = new Thread(this, name);
}
public void run() {
target.test1();
}
}
class NewThread2 implements Runnable {
Thread t;
String name;
Test target;
NewThread2(Test ob, String threadname) {
target = ob;
name = threadname;
t = new Thread(this, name);
}
public void run() {
synchronized(target) {
target.test1();
}
}
}
class Test1 {
public static void main(String args[]) {
Test ob = new Test();
NewThread1 t1 = new NewThread1(ob, "t1");
NewThread2 t2 = new NewThread2(ob, "t2");
t2.t.start();
t1.t.start();
try {
t1.t.join();
t2.t.join();
} catch(InterruptedException e) {
System.out.println("Main thread interrupted");
}
System.out.println("Main thread exiting");
}
}