本帖最后由 asvsass 于 2014-2-18 18:29 编辑
- <DIV class=blockcode>
- <BLOCKQUOTE>package cn.itcast.bank;
- public class NumberMachine {
- private NumberManage commonManager=new NumberManage();
- private NumberManage expressManager=new NumberManage();
- private NumberManage vipManager=new NumberManage();
- public NumberManage getCommonManager() {
- return commonManager;
- }
- public NumberManage getExpressManager() {
- return expressManager;
- }
- public NumberManage getVipManager() {
- return vipManager;
- }
- private NumberMachine(){}
- public static NumberMachine getInstance(){
- return instance;
- }
- private static NumberMachine instance =new NumberMachine();
- }
复制代码
package cn.itcast.bank;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 1; i <5; i++) {
ServiceWindow commonWindow=new ServiceWindow();
commonWindow.setWindowId(i);
commonWindow.start();
}
ServiceWindow expressWindow=new ServiceWindow();
expressWindow.setType(CustomerType.EXPRESS);
expressWindow.start();
ServiceWindow vipWindow=new ServiceWindow();
vipWindow.setType(CustomerType.VIP);
vipWindow.start();
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Integer num=NumberMachine.getInstance().getCommonManager().generateNewManage();
System.out.println(num+"号普通客户等待服务");
}
},
0,
1,
TimeUnit.SECONDS);
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Integer num=NumberMachine.getInstance().getCommonManager().generateNewManage();
System.out.println(num+"号vip客户等待服务");
}
},
0,
6,
TimeUnit.SECONDS);
Executors.newScheduledThreadPool(1).scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Integer num=NumberMachine.getInstance().getCommonManager().generateNewManage();
System.out.println(num+"号快速客户等待服务");
}
},
0,
2,
TimeUnit.SECONDS);
}
}
打印结果变成8号普通客户等待服务
9号普通客户等待服务
10号快速客户等待服务
11号普通客户等待服务
12号普通客户等待服务
13号vip客户等待服务
14号快速客户等待服务
变成数据共享了
而老师的是
1号普通
1号快速
1号vip
- package cn.itcast.bank;
- import java.util.List;
- import java.util.ArrayList;
- public class NumberManage {
- private int LastNumber=0;
- private List<Integer> queueNumber=new ArrayList<Integer>();
- public synchronized Integer generateNewManage(){
- queueNumber.add(++LastNumber);
- return LastNumber;
- }
- public synchronized Integer FetchServiceNumber(){
- if(queueNumber.size()>0)
- return queueNumber.remove(0);
- return null;
- }
- }
复制代码
|