首页 > 编程语言 > 详细

Java程序测试之线程的同步

时间:2015-03-18 17:17:10      阅读:283      评论:0      收藏:0      [点我收藏+]
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();
    }
}

 

Java程序测试之线程的同步

原文:http://www.cnblogs.com/ghmgm/p/4347731.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!