码迷,mamicode.com
首页 > 编程语言 > 详细

Servlet模拟网上售票问题,解决线程的安全问题

时间:2014-09-02 14:13:44      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:servlet模拟网上售票问题   解决线程的安全问题   myeclipse   servlet   

package com.lc.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Ticketsell extends HttpServlet {


	public int ticket = 3;//假设只有三张票
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=gbk");
		
		
		//简单点而处理售票问题
		//当一个变量需要多个用户共享,则应该在访问该变量的时候加 同步机制
		//如果一个变量不需要共享则直接在doGet()和doPost()方法中定义即可,这样的话就不存在线程的安全型问题
		
		
		synchronized (this) { //解决同步性问题的方法
			
			if(ticket > 0)
			{
				System.out.println("你买到票了!");
				out.println("你买到票了!");
			
				//休眠
				try {
					Thread.sleep(10*1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ticket--;
			}
			else
			{
				System.out.println("你没有买到票!");
				out.println("你没有买到票!");
			}
		}
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
				
		this.doGet(request, response);

	}



}



运行结果如下:在不同的游览器中同时访问这个资源  在第三次之后显示 票没有了!

bubuko.com,布布扣

Servlet模拟网上售票问题,解决线程的安全问题

标签:servlet模拟网上售票问题   解决线程的安全问题   myeclipse   servlet   

原文地址:http://blog.csdn.net/xlgen157387/article/details/39004957

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!