java多线程实现卖票小程序

时间:2024-01-01 19:04:09
 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--);
} }
}
利用多线程实现的简单模拟卖票。