首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java亟需关注的知识点-并发之后台线程

2012-09-21 
java需要关注的知识点---并发之后台线程所谓的后台线程,是指在程序运行的时候在后台提供一种通用服务的线

java需要关注的知识点---并发之后台线程
所谓的后台线程,是指在程序运行的时候在后台提供一种通用服务的线程,并且这种线程并不属于程序中不可或缺的部分。因此,当所有的非后台线程结束的时候,程序也就终止,同时会杀死所有的后台线程。

package com.thread;import java.util.concurrent.TimeUnit;public class SimpleDaemons implements Runnable{public void run() {while(true) {try {TimeUnit.MILLISECONDS.sleep(100);System.out.println(Thread.currentThread() + " " + this);} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 10; i++) {Thread daemo = new Thread(new SimpleDaemons());daemo.setDaemon(true);daemo.start();}System.out.println("All daemons started");//如果去掉sleep,run方法中的语句不会输出。说明main也是非后台线程TimeUnit.MILLISECONDS.sleep(180);}}


实例 2 :
package com.thread;import java.io.IOException;public class ResponsveUI extends Thread {private static volatile double d = 1;public ResponsveUI() {setDaemon(true);start();}public void run() {while(true) {d = d + (Math.PI + Math.E);}}public static void main(String[] args) throws Exception {//new UnresponsiveUI(); //must kill this processnew ResponsveUI();System.in.read();System.out.println(d);}}class UnresponsiveUI {private volatile double d = 1;public UnresponsiveUI() throws Exception{while (d > 0) {d = d + (Math.PI + Math.E);}System.in.read();}}

热点排行