本帖最后由 AJrxin 于 2013-01-17 16:28:59 编辑

解决方案 »

  1.   

    你的程序没让它起作用啊。
    synchronized锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程中执行这个同步方法时,他们之间会形成互斥,达到同步的效果。
    public class ThreadTest {
    private String lock = "lock";
    public ThreadTest() {
    ThreadClass threadClass = new ThreadClass();
    Thread thread = new Thread(threadClass);
    thread.start();
    } public static void main(String[] args) throws Exception {
    ThreadTest threadTest = new ThreadTest();
    threadTest.abc();
    } public synchronized void abc() {
    for (int i = 1; i < 1000; i++) {
    System.out.println("main thread run..." + ":" + i);
    }
    } class ThreadClass implements Runnable { public void run() {
    abc();
    // for (int i = 1; i < 1000; i++) {
    // System.out.println("thread run..." + ":" + i);
    // }
    }
    }
    }
      

  2.   

    谢谢楼上,如果想锁定方法,是不是要改为
    public void abc() {
          synchronized(lock){
            for (int i = 1; i < 1000; i++) {
                System.out.println("main thread run..." + ":" + i);
            }
          }
        }
      

  3.   

    synchronized 方法 = synchronized(this)