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();
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。