class TestSyn implements Runnable{
Timer timer = new Timer();
public static void main(String args[]){
Thread t1 = new Thread (new TestSyn(),"t1");
Thread t2 = new Thread (new TestSyn(),"t2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}class Timer{
private static int num = 0;
public synchronized void add(String name){
num++;
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name + "是第" + num + "个使用timer的线程");
}
}
/*结果是:
t1是第2个使用timer的线程
t2是第2个使用timer的线程*/同步了怎么没有起作用?我要的结果应该是:
t1是第1个使用timer的线程
t2是第2个使用timer的线程什么叫对象锁和释放对象锁?锁住和释放的是哪个对象?timer对象?怎么释放对象锁的?刚看,不懂
太复杂的术语看不懂。

解决方案 »

  1.   

            Thread t1 = new Thread (new TestSyn(),"t1");
            Thread t2 = new Thread (new TestSyn(),"t2");
            t1.start();
            t2.start();改成
    TestSyn ts = new TestSyn();
            Thread t1 = new Thread (ts,"t1");
            Thread t2 = new Thread (ts,"t2");
            t1.start();
            t2.start();试试
      

  2.   


    class TestSyn implements Runnable{
        Timer timer = new Timer();
        public static void main(String args[]){
         TestSyn syn = new TestSyn();
            Thread t1 = new Thread (syn,"t1");
            Thread t2 = new Thread (syn,"t2");
            t1.start();
            t2.start();
        }
        public void run(){
            timer.add(Thread.currentThread().getName());
        }
    }class Timer{
        private static int num = 0;
        public synchronized void add(String name){
            num++;
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name + "是第" + num + "个使用timer的线程");
        }
    }
      

  3.   

    锁住和释放的是哪个对象?timer对象?
    对象锁是timer,同一对象时,才有效果。
      

  4.   


    Timer timer = new Timer();改成static Timer timer = new Timer();
      

  5.   

    这样 Timer 就是单子模式了
      

  6.   


    class TestSyn implements Runnable{
    Timer timer = new Timer();
    public static void main(String args[]){
    TestSyn syn = new TestSyn();
    Thread t1 = new Thread (syn,"t1");
    Thread t2 = new Thread (syn,"t2");
    t1.start();
    t2.start();
    }
    public void run(){
    timer.add(Thread.currentThread().getName());
    }
    }class Timer{
    private static int num = 0;
    public void add(String name){
    synchronized(this){
    num++;
    try{
    Thread.sleep(1000);
    }catch(InterruptedException e){
    e.printStackTrace();
    }
    System.out.println(name + "是第" + num + "个使用timer的线程");
    }
    }
    }
    写法2,和第一种写法有什么区别啊?
      

  7.   


            TestSyn syn = new TestSyn();
            Thread t1 = new Thread (syn,"t1");
            Thread t2 = new Thread (syn,"t2");
    两个线程竞争同一个对象syn