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

synchronized 同步方法不起作用
本帖最后由 AJrxin 于 2013-01-17 16:28:59 编辑
public class ThreadTest {
  2     private String lock = "lock";
  3 
  4     public ThreadTest(){
  5         ThreadClass threadClass = new ThreadClass();
  6         Thread thread = new Thread(threadClass);
  7         thread.start();
  8     }
  9 
 10     public static void main(String[] args) throws Exception {
 11         ThreadTest threadTest = new ThreadTest();
 12         threadTest.abc();
 13     }
 14 
 15     public synchronized void abc() {
 16             for (int i = 1; i < 1000; i++) {
 17                 System.out.println("main thread run..." + ":" + i);
 18             }
 19     }
 20 
 21     class ThreadClass implements Runnable {
 22 
 23         public void run() {
 24             for (int i = 1; i < 1000; i++) {
 25                 System.out.println("thread run..." + ":" + i);
 26             }
 27         }
 28     }
 29 }

这段代码对abc函数加锁synchronized void abc(),为什么不起作用? 谢谢。

------解决方案--------------------
你的程序没让它起作用啊。
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);