public synchronized void aa() {
System.out.println("aa method");
try {
Thread.sleep(10000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void bb() {
System.out.print("bb method");
}
private static final C c = new C();
public static void main(final String[] args) {
new Thread(new Runnable() {
@Override public void run() {
c.aa();
}
}).start();
new Thread(new Runnable() {
@Override public void run() {
c.bb();
}
}).start();
}
}
class C {
public synchronized void aa() {
System.out.println("aa method");
try {
Thread.sleep(10000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void bb() {
System.out.print("bb method");
}
public static void main(final String[] args) {
final ThreadA threadA = new ThreadA();
threadA.setName("A");
threadA.start();
final ThreadB threadB = new ThreadB();
threadB.setName("B");
threadB.start();
}
}
class Service {
public void printA() {
synchronized (Service.class) {
System.out.println("線程" + Thread.currentThread().getName() + "進入printA");
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(10000);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.out.println("線程" + Thread.currentThread().getName() + "離開printA");
}
}
public void printB() {
synchronized (Service.class) {
System.out.println("線程" + Thread.currentThread().getName() + "進入printB");
System.out.println(Thread.currentThread().getName());
System.out.println("線程" + Thread.currentThread().getName() + "離開printB");
}
}
}
class ThreadA extends Thread {
@Override public void run() {
new Service().printA();
}
}
class ThreadB extends Thread {
@Override public void run() {
new Service().printB();
}