1.两个方法加 synchronized,一个线程进去sleep,另一个线程可以进入到另一个方法吗?
- 答案:不能,因为synchronized会锁住当前实例对象,除非另一个方法没有synchronized修饰。
如下程序,先输出22222222,再输出111111111.
不加synchronized的方法是不受影响的。
public class Main {
public static void main(String[] args) {
Test test = new Test();
Thread t1 = new Thread(){
public void run(){
test.test1();
}
};
Thread t2 = new Thread(){
public void run(){
test.test2();
}
};
t1.start();
t2.start();
}
}
class Test{
public synchronized void test1(){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("11111111");
}
public static void test2(){
System.out.println("22222222");
}
}