多线程 同步问题

public class TicketDemo 
{
    public static void main(String[] args) 
    {
        Ticket t=new Ticket();
        Thread t1=new Thread(t);
        t1.setName("One--");
        t1.start();
        Thread t2=new Thread(t);
        t2.setName("Two--");
        t2.start();
        Thread t3=new Thread(t);
        t3.setName("Three--");
        t3.start();
    }
}
class Ticket implements Runnable
{
    private int tick=100;
    Object obj=new Object();
    public void run()
    {
        while(true)
        {
            synchronized(obj)
            {
                if(tick>0)
                {
                    try
                    {
                        Thread.sleep(10);
                    }
                    catch (InterruptedException e)
                    {
                        System.out.println("中断异常");
                    }
                    System.out.println(Thread.currentThread().getName()+tick--);
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zhujialei123/p/9349871.html