public class test1 implements java.lang.Runnable{   
public synchronized void run() { 
System.out.println("线程开始:");
int num = 1;   
for (int i = 0; i < 3; i++) {   
num = num + 1;   
try {   
Thread.sleep(2000);   
} catch (InterruptedException e) {   
e.printStackTrace();   
}   
System.out.println("num is value +==="+Thread.currentThread().getName()+"---------" + num);   
}   
System.out.println("线程结束!");
}   
}
public class TestMan {   
    public static void main(String[] args) {
     for(int i=0;i<5;i++){
        Runnable safe=new test1();   
        Thread thread1=new Thread(safe);   
        thread1.start();   
     }
    }   
   

运行结果为:线程开始:
线程开始:
线程开始:
线程开始:
线程开始:
num is value +===Thread-4---------2
num is value +===Thread-0---------2
num is value +===Thread-2---------2
num is value +===Thread-1---------2
num is value +===Thread-3---------2
num is value +===Thread-4---------3
num is value +===Thread-0---------3
num is value +===Thread-2---------3
num is value +===Thread-1---------3
num is value +===Thread-3---------3
num is value +===Thread-0---------4
线程结束!
num is value +===Thread-2---------4
线程结束!
num is value +===Thread-4---------4
线程结束!
num is value +===Thread-1---------4
线程结束!
num is value +===Thread-3---------4
线程结束!

线程3为什么没等线程1结束就开始执行synchronized 里的代码?纠结啊!

解决方案 »

  1.   

    这是正常的.
    你在main()里循环产生了5个safe对象,每个对象对应着一个线程,尽管run()方法加了同步,但只有一个线程运行,不存在同步问题。
    改一下程序:public class TestMan {   
        public static void main(String[] args) {
            Runnable safe=new test1();   //放在循环外边,5个线程公用这一个对象,这时结果会出来了。
            for(int i=0;i<5;i++){
            //Runnable safe=new test1();   
            Thread thread1=new Thread(safe);   
            thread1.start();   
            }
        }   
       

      

  2.   

    谢谢回答 
    能再问您个问题吗,怎么才能模拟一次servlet访问?
      

  3.   

    public class TestMan {   
        public static void main(String[] args) {
           Runnable safe=new test1(); 
            for(int i=0;i<5;i++){
            Thread thread1=new Thread(safe);   
            thread1.start();   
            }
        }   
       
    } 这样试试看……
      

  4.   

    谢谢你,我想问个菜鸟问题:
    我想摸你多次访问servlet是该这样写:
     1、   public static void main(String[] args) {
           Runnable safe=new test1(); 
            for(int i=0;i<5;i++){
            Thread thread1=new Thread(safe);   
            thread1.start();   
            }
        }   
    2、还是:
        public static void main(String[] args) {
            for(int i=0;i<5;i++){
            Runnable safe=new test1();   
            Thread thread1=new Thread(safe);   
            thread1.start();   
            }
    因为servlet是单例的,我觉得应该是第一种才对的。
    但有个事实让我非常郁闷,我们系统遇到一个怪异的问题:
    每次访问servlet,调用一个加synchronized线程安全的方法,但这个方法居然出现了不同步。
    我用上述main方法模拟访问servlet开多个线程同时调用那个线程安全的方法。方法1没出现不同步的情况。
    方法2因为是多个实例所以不同步了。
    有谁知道servlet,调用一个加synchronized线程安全的方法,为什么这个方法居然出现了不同步吗?