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

并发(2)

2012-12-26 
并发(二)1:后台线程(守护线程)后台线程一半用来提供一种通用服务,不属于程序中不可或缺的部分。所有的非后

并发(二)

1:后台线程(守护线程)

后台线程一半用来提供一种通用服务,不属于程序中不可或缺的部分。所有的非后台线程结束时,进程会杀死所有的后台线程。后台进程在不执行finally方法的情况下就有可能结束run方法

public class SimpleDaemos implements Runnable {public static void main(String[] args) throws InterruptedException {for(int i=0;i<10;i++) {Thread daemo = new Thread(new SimpleDaemos());daemo.setDaemon(true);daemo.start();}System.out.println("All daemo started");TimeUnit.MILLISECONDS.sleep(175);}public void run() {try {while(true) {TimeUnit.MILLISECONDS.sleep(100);System.out.println(Thread.currentThread() + " " + this);}} catch (InterruptedException e) {System.out.println("sleep() interrupted");}}}

?

2:ThreadFactory定制线程属性

public class DaemonFromFactory implements Runnable{public static void main(String[] args) throws InterruptedException {//使用一个线程工厂作为参数,创建的线程具有线程工厂的属性ExecutorService exe = Executors.newCachedThreadPool(new DaemoThreadFactory());for(int i=0;i<10;i++) {exe.execute(new DaemonFromFactory());}System.out.println("All daemos started");TimeUnit.MILLISECONDS.sleep(500);}public void run() {}}/** * 使用线程工厂创建出来的线程全部是守护线程 * @author zhuchangxin * */class DaemoThreadFactory implements ThreadFactory {public Thread newThread(Runnable r) {Thread t = new Thread(r);t.setDaemon(true);return t;}}

3:join()加入一个线程

在a线程上调用b.join()。则a线程等待b执行完,然后才继续执行。如果期间调用interrupt()方法打断线程,则b线程被打断,a继续向下执行

public class Joining {public static void main(String[] args) throws InterruptedException {Sleeper sleepy = new Sleeper("Sleepy" , 1500);// 1Sleeper grumpy = new Sleeper("Grumpy" , 1500);// 2Joiner dopey = new Joiner("Dopey", sleepy);// 3Joiner doc = new Joiner("Doc", grumpy);// 4Thread.sleep(500);grumpy.interrupt();}}class Sleeper extends Thread {private int duration;public Sleeper(String name,int sleepTime) {super(name);this.duration = sleepTime;start();}public void run() {try {TimeUnit.MILLISECONDS.sleep(duration);// 5} catch (InterruptedException e) {//调用Thread父类中的getName方法System.out.println(getName() + " was interrupted. isInterrupted(): " + isInterrupted());return ;}System.out.println(getName() + " has awakened");}}class Joiner extends Thread {private Sleeper sleeper;public Joiner(String name,Sleeper sleeper) {super(name);this.sleeper = sleeper;start();}public void run() {try {sleeper.join();}catch (InterruptedException e) {System.out.println("Interrupted");}System.out.println(getName() + " join completed");}}输入结果:Grumpy was interrupted. isInterrupted(): falseDoc join completedSleepy has awakenedDopey join completed

?4:捕获异常

我们无法捕获从线程中逃逸的异常,一旦异常逃出run方法,它将会向控制台输出,即便使用将main主体放到try,catch中

public class SimpleDaemos implements Runnable {public static void main(String[] args) {try {for(int i=0;i<10;i++) {Thread daemo = new Thread(new SimpleDaemos());daemo.setDaemon(true);//设成守护线程daemo.start();}System.out.println("All daemo started");TimeUnit.MILLISECONDS.sleep(175);} catch(Exception e) {}}public void run() {try {throw new InterruptedException();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}控制台仍会输出异常

?

解决方法:可以Thread.UncaughtExceptionHandler接口,该接口在线程因未捕获的异常临近死亡时调用

public class CaptureUncaughtException {public static void main(String[] args) {ExecutorService exe = Executors.newCachedThreadPool(new HandlerThreadFactory());exe.execute(new ExceptionThread2());}}class ExceptionThread2 implements Runnable {@Overridepublic void run() {Thread t = Thread.currentThread();System.out.println("run() by " + t);System.out.println("eh = " + t.getUncaughtExceptionHandler());throw new RuntimeException();}}//创建一个线程工厂,由该工厂创建的线程使用自定义异常类作为默认的异常处理方法class HandlerThreadFactory implements ThreadFactory {@Overridepublic Thread newThread(Runnable r) {Thread t = new Thread(r);t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());System.out.println("eh = " + t.getUncaughtExceptionHandler());return t;}}//自定义异常类class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {@Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println("caught " + e);}}

?

?

热点排行