您的位置:首页 > 移动开发 > 微信开发

java多线程实现卖票小程序

2015-09-02 20:02 603 查看
package shb.java.demo;
/**
* 多线程测试卖票小程序。
* @Package:shb.java.demo
* @Description:
* @author shaobn
* @Date 2015-9-2下午7:49:53
*/
public class TestSyn {
public static void main(String[] args) {
//此注释为实现方式一
/*TicketDemo td = new TicketDemo();
Thread t1 = new Thread(td);
Thread t2 = new Thread(td);
t1.start();
t2.start();*/
//为实现方式二
TicketDemo2 td2 = new TicketDemo2();
Thread t3 = new Thread(td2);
Thread t4 = new Thread(td2);
t3.start();
t4.start();
}
}
/**
* 卖票的类(实现方式一)
* @Package:shb.java.demo
* @Description:
* @author shaobn
* @Date 2015-9-2下午7:44:45
*/
class TicketDemo implements Runnable{
private int ticket = 200;
public void run(){
while(true){
synchronized(this){
if(ticket>0){
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(Thread.currentThread()+"***"+"票数为"+ticket--);
}
}
}
}

}
/**
* 卖票的类(实现方式二)
* @Package:shb.java.demo
* @Description:
* @author Shihaobin
* @Date 2015-9-2下午7:51:56
*/
class TicketDemo2 implements Runnable{
public int ticket = 200;
public void run(){
while(true){
show();
}
}
//实现对多线程程序的封装
public synchronized void show(){
if(ticket>0){
try {
Thread.sleep(100);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(Thread.currentThread()+"***"+"票数为"+ticket--);
}

}
}
利用多线程实现的简单模拟卖票。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: