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

关于synchronized!
各位谁知道我这程序怎么一直都一个线程工作啊?去掉synchronized后多线程。怎么回事啊?

Java code
class TestSynchronized
{
    public static void main(String[] args)
    {
        Ticket t = new Ticket();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
    }
}

class Ticket implements Runnable
{
    int ticket = 100;
    String str = new String("");
    public void run()
    {
        while(true)
        {
            /*synchronized(str)
            {
                if(ticket > 0)
                {
                    try
                    {Thread.sleep(100);}
                    catch(Exception e){}
                    System.out.println(Thread.currentThread().getName() + "   :sales a ticket:" + ticket--);
                }
            }*/
            sale();
        }
    }
    
    public synchronized void sale()
    {
        if(ticket > 0)
                {
                    try{Thread.sleep(100);}
                    catch(Exception e){}
                    System.out.println(Thread.currentThread().getName() + "   :sales a ticket:" + ticket--);
                }
    }
}


------解决方案--------------------
楼主的程序,为什么就出现单一线程在运行呢?
或许是运行时间短的原因。理论上是三个线程都有机会运行的。但楼主程序的问题是,在同步方法里,虽然运行Thread.sleep(100), 但别的线程并不能在此时运行,因为这个同步对象的锁不释放。
要象解决问题,很简单:把休眠放在同步方法的外边。

Java code

public class TestSynchronized
{
    public static void main(String[] args)
    {
        Ticket t = new Ticket();
        new Thread(t).start();
        new Thread(t).start();
        new Thread(t).start();
    }
}

class Ticket implements Runnable
{
    int ticket = 100;
    String str = new String("");                //这个str用于同步目的。
    public void run()
    {
        while(true)
        {   
        try
        {
            Thread.sleep(100);
        }
            catch(Exception e)
        {
            e.printStackTrace();            // 最好加上.
        }
                synchronized(str)
                {
                    if(ticket > 0)
                    {
                        System.out.println(Thread.currentThread().getName() + "   :sales a ticket:" + ticket--);
                    }
                }

            if(ticket<=0)                    //票卖完让程序退出。
            break;
        }//end while
    }//end run
    
}

------解决方案--------------------
我试过了,你让程序多运行几次就不是只有一个线程了
------解决方案--------------------
探讨

我试过无数遍了,确实是只有第一个new出来的线程运行,很纳闷,就算是线程睡眠的时候其他线程不能运行,其他时间总能让别的线程运行吧?