Java程序测试之线程的同步

package tickect;

class ticketnum implements Runnable
{
    public int tickets = 100;
    String str = new String();
    public void run()
    {
        while(true)
        {
            synchronized(str)
            {
                if (tickets>0)
                {
                    System.out.printf("The Thread: %s is selling the %dth ticket!\n",Thread.currentThread().getName(),tickets);
                    --tickets;
                    try
                    {
                        Thread.sleep(20);
                    }
                    catch(Exception e)
                    {}
                }
                else
                {
                    break;
                }
            }
        }
    }
    
}

public class Tickect_test {

    public static void main(String [] args)
    {
        ticketnum ticketNum = new ticketnum();
        Thread sellThread1 = new Thread (ticketNum);
        Thread sellThread2 = new Thread (ticketNum);
        sellThread1.start();
        sellThread2.start();
    }
}
原文地址:https://www.cnblogs.com/ghmgm/p/4347731.html