面试笔记(二)
今天遇到一个面试题
public static synchronize void a()
public synchronize void b()
问题:现在存在着两个方法,如果线程A开始执行方法a(),那么另一个线程是否可以执行方法b()?
我的想法:
static修饰的方法,synchronize关键词所用的锁为class对象
普通方法,synchronize关键词所用的锁为类对象
锁不一致,所用可以访问。
简单代码展示
public class TestThread1 {
public static synchronized void a() throws InterruptedException {
System.out.println("a执行开始-----");
Thread.sleep(5000);
System.out.println("a执行完成-----");
}
public synchronized void b() throws InterruptedException {
System.out.println("b执行开始-----");
Thread.sleep(5000);
System.out.println("b执行完成-----");
}
}
public class TestThread2 {
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
try {
TestThread1.a();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread(){
@Override
public void run() {
try {
new TestThread1().b();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
执行结果如下:
image.png
我的想法应该是正确的。