java 7 concurrency cookbook,Java 7 Concurrency Cookbook 翻译 第一章 线程管理之四

七、创建和运行一个后台线程

Java中有一种特别的线程叫做 deamon(后台) 线程。这类线程具有非常低的权限,并且只有在同一个程序中没有其他的正常线程在运行时才会运行。注意:当一个程序中只剩下后台线程时,JVM会终结所有的后台线程并结束程序。

由于这个特性,后台线程一般用于为同一个程序中的其他正常线程提供服务。这种后台线程一般都有一个无限的循环在等待请求服务或者执行请求的任务。由于不知道它们何时可以获得CPU的调用执行,同时在没有其他正常线程的情况下会被JVM终结,所以后台线程不能用于执行重要的任务。后台线程的一个典型应用是Java中的垃圾回收器。

本秘诀中,我们将学习如何创建具有两个线程的程序:一个正常线程在一个队列上写事件,另一个后台线程负责清理该队列上10秒之前生成的事件。

public class CleanerTask extendsThread {private Dequedeque;public CleanerTask(Dequedeque) {this.deque =deque;

setDaemon(true);

}

@Overridepublic voidrun() {while (true) {

Date date= newDate();

clean(date);

}

}private voidclean(Date date) {longdifference;booleandelete;if (deque.size() == 0) {return;

}

delete= false;do{

Event e=deque.getLast();

difference= date.getTime() -e.getDate().getTime();if (difference > 1000) {

System.out.println("Cleaner: "+ e.getEvent() +"\n");

deque.removeLast();

delete= true;

}

}while (difference > 1000);if(delete) {

System.out.printf("Cleaner: Size of the queue: "+ deque.size() +"\n");

}

}

}public classEvent {privateDate date;privateString event;publicDate getDate() {returndate;

}public voidsetDate(Date date) {this.date =date;

}publicString getEvent() {returnevent;

}public voidsetEvent(String event) {this.event =event;

}

}public classMain {public static voidmain(String[] args) {

Deque deque = new ArrayDeque();

WriterTask writer= newWriterTask(deque);for (int i = 0; i < 3; i++) {

Thread thread= newThread(writer);

thread.start();

}

CleanerTask cleaner= newCleanerTask(deque);

cleaner.start();

}

}public class WriterTask implementsRunnable{private Dequedeque;public WriterTask(Dequedeque) {this.deque =deque;

}

@Overridepublic voidrun() {for (int i = 1; i < 20; i++) {

Event event= newEvent();

event.setDate(newDate());

event.setEvent(String.format("The thread %s has generated " +

"an event", Thread.currentThread().getId()));

deque.addFirst(event);try{

TimeUnit.SECONDS.sleep(1);

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

}

注意:setDeamon() 方法必须在 start() 方法前调用才有效。一旦线程启动,就不能修改其是否为后台线程了。同时,可以使用 isDeamon() 方法来判断线程是否为后台线程。

八、处理线程中未控制的异常

Java中有两类异常:

(A) 检测异常:必须捕获或者抛出。

(B) 不检测异常:可以不捕获。

因为 Thread 对象的 run() 方法不能抛出异常,所以出现在此方法中的检测异常都必须捕获。当 run() 方法中抛出不检测异常时,Thread 对象的默认行为是写线程堆栈信息到控制台,然后退出程序。

幸运的是,Java提供了让我们可以捕获和转换未检测异常的机制,使得我们可以避免由于 run() 方法中异常的抛出而导致的程序终结。

Java中有一个 UncaughtExceptionHandler 接口来处理未捕获的异常。

public class ExceptionHandler implementsUncaughtExceptionHandler{

@Overridepublic voiduncaughtException(Thread t, Throwable e) {

System.out.println("An exception has been captured");

System.out.println("Thread: " +t.getId());

System.out.println("Exception: " + e.getClass().getName() + ": "

+e.getMessage());

System.out.println("Stack Trace: ");

e.printStackTrace(System.out);

System.out.println("Thread status: " +t.getState());

}

}public classMain {public static voidmain(String[] args) {

Task task= newTask();

Thread thread= newThread(task);

thread.setUncaughtExceptionHandler(newExceptionHandler());

thread.start();

}

}public class Task implementsRunnable {

@Overridepublic voidrun() {

Integer.parseInt("TTT");

}

}

当线程中有一个异常抛出来时,JVM首先检查该线程是否有设置线程异常处理器,如果有就调用该处理器处理该异常。如果没有,JVM的默认行为是打印线程堆栈信息到控制台,同时推出程序。

注意:Thread 类有一个静态方法 setDefaultUncaughtExceptionHandler() 来为程序中所有的未捕获异常设置处理器。当线程中抛出一个未捕获的异常时:JVM首先查看该线程是否有设置对应的线程异常处理器,如果没有再查看线程所属的线程组是否有设置好线程异常处理器,如果还没有再查看程序是否有设置默认线程异常处理器。

如果没有任何异常处理器存在,JVM就会执行默认行为:写线程栈帧信息到控制台,终止程序的运行。

重要:本系列翻译文档也会在本人的微信公众号(此山是我开)第一时间发布,欢迎大家关注。

20180110214911916742.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
When you work with a computer, you can do several things at once. You can hear music while you edit a document in a word processor and read your e-mail. This can be done because your operating system allows the concurrency of tasks. Concurrent programming is about the elements and mechanisms a platform offers to have multiple tasks or programs running at once and communicate with each other to exchange data or to synchronize with each other. Java is a concurrent platform and offers a lot of classes to execute concurrent tasks inside a Java program. With each version, Java increases the functionalities offered to programmers to facilitate the development of concurrent programs. This book covers the most important and useful mechanisms included in Version 7 of the Java concurrency API, so you will be able to use them directly in your applications, which are as follows: f f t e n . d u o l Basic thread management w.codec w w Thread synchronization mechanisms f f Thread creation and management delegation with executors f f Fork/Join framework to enhance the performance of your application f f Data structures for concurrent programs f f Adapting the default behavior of some concurrency classes to your needs f f Testing Java concurrency applications f f What this book covers Chapter 1, Thread Management will teach the readers how to make basic operations with threads. Creation, execution, and status management of the threads are explained through basic examples. Chapter 2, Basic Thread Synchronization will teach the readers to use the low-level Java mechanisms to synchronize a code. Locks and the synchronized keyword are explained in detail. Chapter 3, Thread Synchronization Utilities will teach the readers to use the high-level utilities of Java to manage the synchronization between the threads in Java. It includes an explanation of how to use the new Java 7 Phaser class to synchronize tasks divided into phases. Chapter 4, Thread Executors will teach the readers to delegate the thread management to executors. They allow running, managing, and getting the results of concurrent tasks. Chapter 5, Fork/Join Framework will teach the readers to use the new Java 7 Fork/Join framework. It’s a special kind of executor oriented to execute tasks that will be divided into smaller ones using the divide and conquer technique. Chapter 6, Concurrent Collections will teach the readers to how to use some concurrent data structures provided by the Java language. These data structures must be used in concurrent programs to avoid the use of synchronized blocks of code in their implementation. Chapter 7, Customizing Concurrency Classes will teach the readers how to adapt some of the most useful classes of the Java concurrency API to their needs. Chapter 8, Testing Concurrent Applications will teach the readers how to obtain information about the status of some of the most useful structures of the Java 7 concurrency API. The readers will also learn how to use some free tools to debug concurrent applications, such as the Eclipse, NetBeans IDE, or FindBugs applications to detect possible bugs on their applications.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值