A类在Java中有2个同步方法,B类有两个静态同步方法,允许2个线程访问这两个方案

时间:2011-06-24 04:27:05

标签: java synchronization thread-safety

public class ThreadTest {
     public static synchronized void m2() {
         System.out.println("static sync m2");
         System.out.println("current"+Thread.currentThread());
         try { Thread.sleep(2000); }
         catch (InterruptedException ie) {}
     }

    public static void main(String[] args) throws InterruptedException {
        Thread t3 = new Thread() {
            public void run() {
                ThreadTest.m2();
            }
        };
        t3.start();
        t3.sleep(2000);
        Thread.sleep(500); // which thread are we sleeping here?
        System.out.println("t3.getState"+t3.getState());
    }
}

如果我们创建另一个线程t1并访问ThreadTest.m2();在里面?是的,这将是允许的,为什么这是静态的和类级别。但是如果我们有非静态方法,则不允许线程1和2访问方法

1 个答案:

答案 0 :(得分:0)