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;//假設(shè)只有三張票
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=gbk");
//簡(jiǎn)單點(diǎn)而處理售票問(wèn)題
//當(dāng)一個(gè)變量需要多個(gè)用戶(hù)共享,則應(yīng)該在訪問(wèn)該變量的時(shí)候加 同步機(jī)制
//如果一個(gè)變量不需要共享則直接在doGet()和doPost()方法中定義即可,這樣的話(huà)就不存在線程的安全型問(wèn)題
synchronized (this) { //解決同步性問(wèn)題的方法
if(ticket > 0)
{
System.out.println("你買(mǎi)到票了!");
out.println("你買(mǎi)到票了!");
//休眠
try {
Thread.sleep(10*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ticket--;
}
else
{
System.out.println("你沒(méi)有買(mǎi)到票!");
out.println("你沒(méi)有買(mǎi)到票!");
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
引發(fā)線程問(wèn)題的思考,小編在之前的學(xué)習(xí)中也遇到過(guò),現(xiàn)在線程問(wèn)題有了一定的理解,希望大家也可以通過(guò)相關(guān)文章得到啟發(fā)。