小弟问我的计算机等级考试二级Java初级练习题目,答案有问题

国家计算机二级考试题目答案出错。 题目如下:

 

问:

当一个线程进入一个对象的一个synchronized方法后,其它线程是否可进入此对象的其它方法?

 

答 : 不可以。synchronized 方法都必须获得调用该方法的类实例的锁方能执行,否则所属线程阻塞,方法一旦执行,就独占该锁,直到从该方法返回时才将锁释放,此后被阻塞的线程才能获得该锁,重新进入可执行状态。

 

这答案明显是错了。

 

假设我们有个类叫Test,里面有个synchronized 方法 a(), 同时有个non synchronized 方法b(), 假设有线程T1进入了Test 对象t的方法a,同时线程T2要进入方法b(),这当然是可以了。

 

非同步方法根本就不去check对象锁,为什么不能让b执行? 写个例子

 

package org.gc.java.lang;

public class TestThread extends Thread {
    SynClass synClass;
    public TestThread(SynClass synClass){
        this.synClass = synClass;
    }
   
    public void run(){
        synClass.test();
        System.out.println(Thread.currentThread().getName() + " " + synClass.hashCode());
        synClass.addMore();
    }

  
    public static void main(String[] args) {
        SynClass a = new SynClass();
        for (int i=0; i<3; i++){
            new TestThread(a).start();
        }
    }

}

class SynClass{
    public synchronized void addMore(){
        System.out.println(Thread.currentThread().getName()+ " enter the synchronized block");
        try {
            Thread.currentThread().sleep(5000L);
        } catch (Exception e){
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+ " leave the synchronized block");
    }
   
    public int test(){
        try {
            System.out.println(Thread.currentThread().getName() + " start test method ");
            //Thread.currentThread().sleep(150);
            System.out.println(Thread.currentThread().getName() + " complete test method ");
        }catch (Exception e){
            e.printStackTrace();
        }
        return 1000;
    }
}

 

得到输出:

 

Thread-0 start test method
Thread-0 complete test method
Thread-0 827574
Thread-0 enter the synchronized block
Thread-1 start test method
Thread-1 complete test method
Thread-1 827574
Thread-2 start test method
Thread-2 complete test method
Thread-2 827574
Thread-0 leave the synchronized block
Thread-2 enter the synchronized block
Thread-2 leave the synchronized block
Thread-1 enter the synchronized block
Thread-1 leave the synchronized block

 

说明问题了。

 

你可能感兴趣的:(java,thread)