把代码复制过去跑下就知道了!
class Example {
public static void exec() {
synchronized (Example.class) {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.printf("%s,Hello%d\n", Thread.currentThread()
.getName(), i);
}
}
}
public void exec2() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.printf("%s,Hello%d\n", Thread.currentThread()
.getName(), i);
}
}
}
public synchronized void exec3() {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.printf("%s,Hello%d\n", Thread.currentThread().getName(),
i);
}
}
public synchronized static void exec4() {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.printf("%s,Hello%d\n", Thread.currentThread().getName(),
i);
}
}
public void exec5() {
for (int i = 0; i < 10; i++) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.printf("%s,Hello%d\n", Thread.currentThread().getName(),
i);
}
}
}
public class test2 {
public static void main(String[] args) {
Example example = new Example();
Thread thread1 = new Thread() {
public void run() {
Example.exec();
}
};
Thread thread2 = new Thread() {
public void run() {
example.exec2();//更换成不同的方法尝试
}
};
thread1.start();
thread2.start();
}
}
Synchronized关键字中锁的理解
最新推荐文章于 2024-07-11 23:19:16 发布