您的位置:首页 > 其它

多线程模拟数据采集、显示

2016-10-20 09:29 197 查看
/**
*
*/
package test1;

import java.text.SimpleDateFormat;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
*
* 项目名称:<span style="font-family: Arial, Helvetica, sans-serif;">CountLast60s </span><span style="font-family: Arial, Helvetica, sans-serif;">类名称:</span><span style="font-family: Arial, Helvetica, sans-serif;">CountLast60s </span><span style="font-family: Arial, Helvetica, sans-serif;">类描述: 创建人:admin 创建时间:2016年10月17日 下午5:35:09 修改人:admin</span><span style="font-family: Arial, Helvetica, sans-serif;">
</span> * 修改时间:2016年10月17日 下午5:35:09 修改备注:
*
* @version
*
*/

public class CountLast60s {

private AtomicLong count = new AtomicLong(0); // 总计数

// private int lastSeconds = 60; // 需要统计的时间段

private int precision = 60; // 精度,具体控制的方法应该更复杂

private LinkedBlockingQueue<Long> queue = new LinkedBlockingQueue<Long>(
precision);// 精度越大,队列的长度也越大

private volatile boolean stopped = false;

private long getCountBeforeOneMinutes() {
// LinkedBlockingQueue 用起来方便,同时,也会有约束
// 这边与下面的poll会出现同步问题,
// 解决办法,可以用自己的Queue,加相关的锁,
if (queue.size() == precision)
return queue.peek();

return 0;
}

/**
* 打印当前近60秒的点击数
*/
public void printCountInLast60s() {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("printer works");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
while (!stopped) {
long c = count.get();
long countInLast60s = c - getCountBeforeOneMinutes();
System.out.println("["
+ sdf.format(System.currentTimeMillis()) + "] -- "
+ countInLast60s + "/" + c);
try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}

/**
* 每隔1秒,采集一次
*/
public void gatherVeryMinutes() {

new Thread(new Runnable() {

@Override
public void run() {
while (!stopped) {
if (queue.size() == precision)
queue.poll();
queue.offer(count.get());
System.out.println("每隔1秒,采集一次,队列大小=" + queue.size()
+ "||队列值=" + queue.peek());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}).start();

}

/**
* 模拟网站点击计数
*/
public void emulateWebCount() {
new Thread(new Runnable() {
@Override
public void run() {
while (!stopped) {
long dingLong = (long) (100 * Math.random());
System.out.println("模拟网站点击计数=" + dingLong + "||"
+ "总计数count=" + count);
count.addAndGet(dingLong);

try {
Thread.sleep((long) (1000 * Math.random()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();

}

/**
* @param args
*/
public static void main(String[] args) {
CountLast60s reporter = new CountLast60s();
reporter.gatherVeryMinutes();
reporter.emulateWebCount();
// reporter.printCountInLast60s();

try {
TimeUnit.MINUTES.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
reporter.stopped = true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: