这里是一个应用项目使用生产消费模型的日志类

package cn.study.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import org.junit.Test; /**
* 日志服务
* @author xiaof
*
*/
public class LogWriter {
private final BlockingQueue<String> queue;
private final LoggerThread logger;
private final static int CAPACITY = 500;
private boolean isShutdown; //停止线程 public LogWriter()
{
this.queue = new LinkedBlockingQueue<String>(CAPACITY);
this.logger = new LoggerThread();
} public void start()
{
//判断这个线程是否已经启动
if(!logger.isAlive())
{
logger.start();
}
} public void log(String msg) throws InterruptedException
{
//放入日志队列并阻塞队列
if(!isShutdown)
queue.put(msg);
else
throw new IllegalStateException("日志开关没有打开");
} public boolean isShutdown() {
return isShutdown;
} public void setShutdown(boolean isShutdown) {
this.isShutdown = isShutdown;
} private class LoggerThread extends Thread
{
public void run()
{
try
{
while(true)
{
//从队列中取出队列头数据,并输出,有必要并阻塞队列
System.out.println("这是日志:" + queue.take());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
} @Test
public void test()
{
LogWriter log = new LogWriter();
log.start();
int i = 1;
while(true)
{
try {
Thread.currentThread().sleep(2000);
//把日志放入队列
log.log("这是日志:" + i++); if(i == 3)
{
log.setShutdown(true);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} }

更加可靠的取消日志服务的操作

package cn.study.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; import org.junit.Test; /**
* 日志类添加可靠的取消操作
* @author xiaof
*
*/
public class LogService {
private final BlockingQueue<String> queue;
private final LoggerThread loggerThread;
private boolean isShutdown;
//如果线程停止提交任务,线程不能停,先得吧剩余的任务提交结束
private int reservations;
private final static int CAPACITY = 500; public LogService()
{
//队列长度
this.queue = new LinkedBlockingQueue<String>(CAPACITY);
this.loggerThread = new LoggerThread();
} public void start()
{
//判断这个线程是否已经启动
if(!loggerThread.isAlive())
{
loggerThread.start();
}
} public void log(String msg) throws InterruptedException
{
//放入日志队列并阻塞队列
synchronized(this)
{
if(isShutdown)
throw new IllegalStateException("日志开关没有打开");
++reservations;
}
queue.put(msg);
} public void stop()
{
synchronized(this)
{
isShutdown = true;
}
//中断线程
loggerThread.interrupt();
} private class LoggerThread extends Thread
{
public void run()
{
try
{
while(true)
{
try
{
//对日志类上锁
synchronized(LogService.this)
{
if(isShutdown && reservations == 0)
{
break;//停止线程
}
}
//取出日志信息
String msg = queue.take();
//提交成功一条,对阻塞的数据计数减少一条
synchronized(LogService.this)
{
--reservations;
}
System.out.println(msg);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
finally
{
System.out.println("日志结束..........");
}
}
} @Test
public void test()
{
LogService log = new LogService();
log.start();
int i = 1;
while(true)
{
try {
Thread.currentThread().sleep(2000);
//把日志放入队列
log.log("这是日志:" + i++); if(i == 3)
{
log.stop();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

【JAVA并发编程实战】7、日志服务的更多相关文章

  1. Java并发编程实战---第六章:任务执行

    废话开篇 今天开始学习Java并发编程实战,很多大牛都推荐,所以为了能在并发编程的道路上留下点书本上的知识,所以也就有了这篇博文.今天主要学习的是任务执行章节,主要讲了任务执行定义.Executor. ...

  2. 《java并发编程实战》笔记

    <java并发编程实战>这本书配合并发编程网中的并发系列文章一起看,效果会好很多. 并发系列的文章链接为:  Java并发性和多线程介绍目录 建议: <java并发编程实战>第 ...

  3. 那些年读过的书《Java并发编程实战》和《Java并发编程的艺术》三、任务执行框架—Executor框架小结

    <Java并发编程实战>和<Java并发编程的艺术>           Executor框架小结 1.在线程中如何执行任务 (1)任务执行目标: 在正常负载情况下,服务器应用 ...

  4. 《Java并发编程实战》文摘

    更新时间:2017-06-03 <Java并发编程实战>文摘,有兴趣的朋友可以买本纸质书仔细研究下. 一 线程安全性 1.1 什么是线程安全性 当多个线程访问某个类时,不管运行时环境采用何 ...

  5. Java并发编程实战——读后感

    未完待续. 阅读帮助 本文运用<如何阅读一本书>的学习方法进行学习. P15 表示对于书的第15页. Java并发编程实战简称为并发书或者该书之类的. 熟能生巧,不断地去理解,就像欣赏一部 ...

  6. 【Java并发编程实战】----- AQS(四):CLH同步队列

    在[Java并发编程实战]-–"J.U.C":CLH队列锁提过,AQS里面的CLH队列是CLH同步锁的一种变形.其主要从两方面进行了改造:节点的结构与节点等待机制.在结构上引入了头 ...

  7. 【Java并发编程实战】----- AQS(三):阻塞、唤醒:LockSupport

    在上篇博客([Java并发编程实战]----- AQS(二):获取锁.释放锁)中提到,当一个线程加入到CLH队列中时,如果不是头节点是需要判断该节点是否需要挂起:在释放锁后,需要唤醒该线程的继任节点 ...

  8. 【Java并发编程实战】----- AQS(二):获取锁、释放锁

    上篇博客稍微介绍了一下AQS,下面我们来关注下AQS的所获取和锁释放. AQS锁获取 AQS包含如下几个方法: acquire(int arg):以独占模式获取对象,忽略中断. acquireInte ...

  9. 【Java并发编程实战】-----“J.U.C”:CountDownlatch

    上篇博文([Java并发编程实战]-----"J.U.C":CyclicBarrier)LZ介绍了CyclicBarrier.CyclicBarrier所描述的是"允许一 ...

  10. 【Java并发编程实战】-----“J.U.C”:CyclicBarrier

    在上篇博客([Java并发编程实战]-----"J.U.C":Semaphore)中,LZ介绍了Semaphore,下面LZ介绍CyclicBarrier.在JDK API中是这么 ...

随机推荐

  1. org.artofsolving.jodconverter.office.OfficeException: failed to start and connect

    org.artofsolving.jodconverter.office.OfficeException: failed to start and connect docviewer 调用 openo ...

  2. GridView中数据的汇总方法

    首先,在页面添加事件<ASP:GridView OnRowDataBound="Gridview1_DataBound"> 其次,后台具体方法: public void ...

  3. TSql 巧用Alt 键

    1,查看表的信息 在TSql 编辑器中,选中一个表,如图 点击Alt+F1,就可以查看表的属性定义 2,使用alt批量插入逗号 在Tsql中使用 in 子句,在(value_List)列表中,经常有很 ...

  4. 如何变相的绕过QQ邮箱订阅的繁琐核审

    先看看正常流程:http://open.mail.qq.com/ 点击“接入订阅”==>申请接入==>登录一下 选择接入完全免费 大概流程就是这样: 下面我们说说快速接入的方法: 1.登录 ...

  5. LINQ系列:LINQ to SQL Join连接

    1. 一对多 var expr = context.Products .Where(p => p.Category.CategoryName == "LINQ to SQL" ...

  6. Bower : ENOGIT git is not installed or not in the PATH

    解决方法一: 添加git到window的环境变量中.设置path路径为C:\Program Files\Git\bin 解决方法二: $ set PATH=%PATH%;C:\Program File ...

  7. OpenCASCADE Make Primitives-Box

    OpenCASCADE Make Primitives-Box eryar@163.com Abstract. By making a simple box to demonstrate the BR ...

  8. sublime text学习

    Ctrl + /  ---------------------注释 Ctrl + 滚动 --------------字体变大/缩小 Ctrl + N-------------------新建 软件右下 ...

  9. 创建 flat network - 每天5分钟玩转 OpenStack(87)

    上一节我们讨论了 flat network 的原理,今天就来创建 "flat_net" 并分析底层网络的实现. 打开菜单 Admin -> Networks,点击 “Crea ...

  10. codefordream 关于js初级训练

    这里的初级训练相对简单,差不多都是以前知识温习. 比如输出“hello world”,直接使用console.log()就行.注释符号,“//”可以注释单行,快捷键 alt+/,"/*   ...