多线程-卖票

多线程-卖票

卖票的线程.

package com.carlinfo.thread.prod.ticket;

/**
 * 卖票的线程
 * @author WangshMac
 */
public class TicketThread implements Runnable
{
	/* 确定所有的线程共用一份资源 */
	private static int total = 20 ;
	/* 所有的TicketThread共用的一个对象Object;
	 * 并且也是一个引用类型 */
	private static Object obj = new Object();
	
	public void run_1()
	{
		/* 循环卖票 */
		while(total > 0 )
		{
			/* 在休息的500毫秒以内,其它的3个线程也可以进来;
			 * 票的数量在最后才开始减1 */
			try
			{
				/* 线程休息一会 */
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread() + "==卖票=>" + total);
			/* 卖票,总数量-1 */
			total = total - 1 ;
		}
	}
	
	public void run_2()
	{
		/* 循环卖票 */
		while(total > 0 )
		{
			/* 在休息的500毫秒以内,其它的3个线程也可以进来;
			 * 票的数量在最后才开始减1 */
			try
			{
				/* 线程休息一会 */
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			/**
			 * 锁的范围越小越好
			 * 小括号中放的就是锁;
			 * 	得是一个引用类型
			 * 	得所有的方法共用一把锁
			 */
			synchronized(obj)
			{
				/**
				 * 3个线程只能有一个线程进入到锁的代码中;
				 * 不管是哪个线程进来了,先判断一下,还有木有票;
				 * 如果有的话,再卖,如果木有,直接跳过,啥也不打印
				 */
				if(total > 0 )
				{
					System.out.println(Thread.currentThread() + "==卖票=>" + total);
					/* 卖票,总数量-1 */
					total = total - 1 ;
				}
			}
		}
	}
	
	public void run()
	{
		/* 循环卖票 */
		while(total > 0 )
		{
			/* 在休息的500毫秒以内,其它的3个线程也可以进来;
			 * 票的数量在最后才开始减1 */
			try
			{
				/* 线程休息一会 */
				Thread.sleep(500);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			/* 卖票 */
			/*this.sell();*/
			
			/* synchronized(this)这种写法和在sell方法上面加上synchronized
			 * 效果一样 */
			synchronized(this)
			{
				/**
				 * 3个线程只能有一个线程进入到锁的代码中;
				 * 不管是哪个线程进来了,先判断一下,还有木有票;
				 * 如果有的话,再卖,如果木有,直接跳过,啥也不打印
				 */
				if(total > 0 )
				{
					System.out.println(Thread.currentThread() + "==卖票=>" + total);
					/* 卖票,总数量-1 */
					total = total - 1 ;
				}
			}
		}
	}
	
	/**
	 * 卖票的方法
	 * 锁方法:的效果相当于锁的对象是this
	 * synchronized(this)
	 * {
	 * }
	 */
	public synchronized void sell()
	{
		/**
		 * 3个线程只能有一个线程进入到锁的代码中;
		 * 不管是哪个线程进来了,先判断一下,还有木有票;
		 * 如果有的话,再卖,如果木有,直接跳过,啥也不打印
		 */
		if(total > 0 )
		{
			System.out.println(Thread.currentThread() + "==卖票=>" + total);
			/* 卖票,总数量-1 */
			total = total - 1 ;
		}
	}
}

测试类

package com.carlinfo.thread.prod.ticket;

/**
 * 测试方法
 * @author WangshMac
 */
public class ClientMain
{
	public static void main(String[] args)
	{
		System.out.println("==唐代宗==");
		/*Thread t = new Thread();
		System.out.println("====>" + t);
		Thread curr = Thread.currentThread() ; 
		System.out.println("====>" + curr);*/
		
		/* 启动线程,只能通过Thread.start方法 
		 * 如果使用的是锁的方法,锁的时候使用的是this;
		 * 一定要确定所有的thread对象,共用一个runnable;
		 * */
		TicketThread tt = new TicketThread() ; 
		/* 增加卖票容器 */
		for(int i = 0 ; i < 3 ; i ++)
		{
			/* 启动一个线程
			 * 参数2是线程的名字
			 *  */
			Thread t = new Thread(tt);
			t.start();
		}
		System.out.println("==main方法结束了==");
	}
}

图片: 运行结果

多线程-卖票_第1张图片

你可能感兴趣的:(多线程-卖票)