先分享相关代码:
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);
}
}
运行结果如下:在不同的游览器中同时访问这个资源 在第三次之后显示 票没有了!
引发线程问题的思考,小编在之前的学习中也遇到过,现在线程问题有了一定的理解,希望大家也可以通过相关文章得到启发。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!