
package com.hanlei.test02.test;
import com.hanlei.test02.utils.Product;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
public class TestSever {
// 实例化一个产品对象,生产者和消费者共享该实例
Product product;
// 定时放票
Timer t;
// 总票数
int sum;
public TestSever() {
sum =0;
// 实例化一个产品对象,生产者和消费者共享该实例
product = new Product();
// 创建接收客户端Socket的线程实例,并启动
new Buy().start();
// 买到票通知
new SendClient().start();
// 创建给客户端发送信息的线程实例,定时放票 并启动
t= new Timer();
t.schedule(new SendMsgToClient(), 0,3000);
System.out.println("服务器已启动...");
}
class Buy extends Thread{
public void run() {
// 获取Socket对象的输入流
for(int i=0; i<5;i++){
new Consumer(""+i);
}
}
}
// 消费
class Consumer implements Runnable{
String name;
public Consumer(String name){
this.name = name;
new Thread(this,name).start();
}
public void run(){
product.get();
}
}
// 给所有客户发送信息的线程 放票
class SendMsgToClient extends TimerTask {
public void run() {
try {
// 如果票卖完了或有重新放票不空
if (sum<=100) {
product.put(2);
System.out.println("已放票10张");
sum +=10;
}else{
System.out.println("100张票已放完");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 通知
class SendClient extends Thread {
LinkedList<String> name= product.getNames();
public void run() {
while (true){
if (!name.isEmpty()){
String aa =name.removeLast();
System.out.println("通知 "+aa +" 已经买到票");
}else{
try {
sleep(100);
} catch