日期:2014-05-20  浏览次数:20741 次

问一个synchronized 的问题
假设一个Class如下
public Class A 
{
  ...
  public synchronized void method1 {
  ...
  }

  public synchronized void method2 {
  ...
  }

}

A obj = new A();

如果有1个线程1正在调用 obj 的method1, 是不是另一个线程2就连obj的method2都不能调用?
谢谢

------解决方案--------------------
站在上面的同志们的肩上写了个DEMO代码,刚好帮自己复习一下,希望对你有用。
Java code

package cn.luochengor.csdn;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * synchronized
 * 
 * @Author luochengor
 * @Date Nov 25, 2011
 * @Email luochengor@foxmail.com
 */
public class Synchronized {

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        D d = new D();
        exec.execute(new ThreadA(d));
        exec.execute(new ThreadB(d));    
        }

}

class D {
    public synchronized void method1() {
        try {
            System.out.println("D.method1()");
            System.out.println("method-1 start to sleep.");
            TimeUnit.SECONDS.sleep(1);
            System.out.println("method-1 wake up.");
        } catch (InterruptedException e) {
            System.out.println("method-1 is interrupted.");
        }
    }

    public synchronized void method2() {
        try {
            System.out.println("D.method2()");
            System.out.println("method-2 start to sleep.");
            TimeUnit.SECONDS.sleep(3);
            System.out.println("method-2 wake up.");
        } catch (InterruptedException e) {
            System.out.println("method-2 is interrupted.");
        }
    }
    
    public void unSynchronized() {
        System.out.println("This is unSynchronized method.");
    }
}

class ThreadA implements Runnable {
    private D d;

    public ThreadA(D d) {
        this.d = d;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                System.out.println("ThreadA.run start doing method1().");
                d.unSynchronized();
                d.method1();
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("ThreadA.run is interrupted.");
            }
        }
    }
}

class ThreadB implements Runnable {
    private D d;

    public ThreadB(D d) {
        this.d = d;
    }

    @Override
    public void run() {
        while (!Thread.interrupted()) {
            try {
                System.out.println("ThreadB.run start doing method2().");
                d.unSynchronized();
                d.method2();
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                System.out.println("ThreadB.run is interrupted.");
            }
        }
    }
}