如下java代码:package com.test;public class ThreadTest implements Runnable { private static int i = 0;
private static int j = 0; public void run() {
f1();
f2();
} private void f1() {
synchronized (ThreadTest.class) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("currentThread:"
+ Thread.currentThread().getId());
System.out.println("i:" + (++i) + "currentThread:"
+ Thread.currentThread().getId());
} } private void f2() {
synchronized (ThreadTest .class) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\tcurrentThread:"
+ Thread.currentThread().getId());
System.out.println("j:" + (++j) + "\tcurrentThread:"
+ Thread.currentThread().getId());
} } public static void main(String[] args) { Thread th1 = new Thread(new ThreadTest ());
Thread th2 = new Thread(new ThreadTest ());
Thread th3 = new Thread(new ThreadTest ());
Thread th4 = new Thread(new ThreadTest ());
th1.start();
th2.start();
th3.start();
th4.start(); }
}
为什么f1()和f2()的第二行打印是同步的,而第一行却不同步?注释掉第一行,打印结果如下:
i:1 currentThread:8
j:1 currentThread:8
i:2 currentThread:11
j:2 currentThread:11
i:3 currentThread:9
j:3 currentThread:9
i:4 currentThread:10
j:4 currentThread:10注释掉第二行,打印结果如下:
currentThread:8
currentThread:11
currentThread:11
currentThread:9
currentThread:9
currentThread:10
currentThread:8
currentThread:10