写了个例子验证了一下:- package test;
- import myutil.SOP;
- public class TestSynchronized2 {
- /**
- * @param args
- * @throws InterruptedException
- */
- public static void main(String[] args) throws InterruptedException {
- // TODO Auto-generated method stub
- MySync2 ms1 = new MySync2();
- ms1.setFlag(1);
- MySync2 ms2 = new MySync2();
- ms2.setFlag(2);
- MySync2 ms3 = new MySync2();
- ms3.setFlag(3);
-
- Thread t1 = new Thread(ms1);
- Thread t2 = new Thread(ms2);
- Thread t3 = new Thread(ms3);
- t1.start();
- Thread.sleep(100);
- t2.start();
- t3.start();
- }
- }
- class MySync2 implements Runnable{
- private int flag = 0;
- private static int i = 0;
-
- public void setFlag(int flag) {
- this.flag = flag;
- }
-
- static synchronized void method1() throws InterruptedException{
- i=10;
- Thread.sleep(5000);
- SOP.sop("method1---"+i);
- }
- static synchronized void method2() throws InterruptedException{
- i=20;
- Thread.sleep(2000);
- SOP.sop("method2---"+i);
- }
- void method3() throws InterruptedException{
- i = 1000;
- SOP.sop("method3---"+i);
- }
- @Override
- public void run() {
- switch (flag) {
- case 1:
- try {
- method1();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- break;
- case 2:
- try {
- method2();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- break;
- case 3:
- try {
- method3();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- break;
- default:
- SOP.sop("here is default");
- break;
- }
- // TODO Auto-generated method stub
-
- }
- }
复制代码 结果是:
method3---1000
method1---1000
method2---20
得出的结论是:
静态方法的默认的锁是类本身,所以两个静态的方法是不可能同时被调用的,只有一前一后的顺序。但是非静态方法就不一定了。
上面这个例子的情况是:
t1先把 i 改成10,然后锁上,这时候t2不可以进来了,但是因为t3不受锁的限制,进来把 i 改成1000 并且输出,后来t1醒来后,i 已经变成1000了,所以输出1000,t1释放所后,t2再进来,把 i 改成20,然后输出20.
|