不运行以下几段代码的情况下你能得出输出结果吗? (大神就别看啦,都是很基础的东西)
代码1
package com.ls;
public class Test {
synchronized void fun1() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("fun1() invoked");
}
synchronized void fun2() {
System.out.println("fun2() invoked");
}
public static void main(String[] args) {
Test t = new Test();
Thread t1 = new MyThread("thread1", t);
Thread t2 = new MyThread("thread2", t);
t1.start();
t2.start();
}
}
class MyThread extends Thread {
Test t = null;
public MyThread(String name, Test t) {
super(name);
this.t = t;
}
@Override
public void run() {
if ("thread1".equals(Thread.currentThread().getName())) {
t.fun1();
} else {
t.fun2();
}
}
}
代码2
package com.ls;
public class Test {
synchronized void fun1() {
try {
this.wait();
} catch (InterruptedException e) {
}
System.out.println("fun1() invoked");
}
synchronized void fun2() {
System.out.println("fun2() invoked");
this.notify();
}
public static void main(String[] args) {
Test t = new Test();
Thread t1 = new MyThread("thread1", t);
Thread t2 = new MyThread("thread2", t);
t1.start();
t2.start();
}
}
class MyThread extends Thread {
Test t = null;
public MyThread(String name, Test t) {
super(name);
this.t = t;
}
@Override
public void run() {
if ("thread1".equals(Thread.currentThread().getName())) {
t.fun1();
} else {
t.fun2();
}
}
}
代码3
package com.ls;
public class Test {
synchronized static void fun1() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("fun1() invoked");
}
synchronized void fun2() {
System.out.println("fun2() invoked");
}
public static void main(String[] args) throws Exception {
Test t = new Test();
Thread t1 = new MyThread("thread1", t);
Thread t2 = new MyThread("thread2", t);
t1.start();
Thread.sleep(10);
t2.start();
}
}
class MyThread extends Thread {
Test t = null;
public MyThread(String name, Test t) {
super(name);
this.t = t;
}
@Override
public void run() {
if ("thread1".equals(Thread.currentThread().getName())) {
t.fun1();
} else {
t.fun2();
}
}
}
代码4
package com.ls;
public class Test {
synchronized void fun1() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("fun1() invoked");
}
void fun2() {
System.out.println("fun2() invoked");
}
public static void main(String[] args) {
Test t = new Test();
Thread t1 = new MyThread("thread1", t);
Thread t2 = new MyThread("thread2", t);
t1.start();
t2.start();
}
}
class MyThread extends Thread {
Test t = null;
public MyThread(String name, Test t) {
super(name);
this.t = t;
}
@Override
public void run() {
if ("thread1".equals(Thread.currentThread().getName())) {
t.fun1();
} else {
t.fun2();
}
}
}