码迷,mamicode.com
首页 > 编程语言 > 详细

从头认识java-18.2 基本的线程机制(8)多线程的异常捕捉

时间:2016-01-21 13:58:44      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

这一章节我们来讨论一下多线程的异常捕捉。

1.普通情况的异常

package com.ray.ch17;

public class Test {

	public static void main(String[] args) {
		try {
			new ThreadA().run();
		} catch (Exception e) {
			System.out.println("捕捉到异常");
		}
	}
}

class ThreadA implements Runnable {

	@Override
	public void run() {
		throw new RuntimeException();
	}
}

输出:

捕捉到异常


2.多线程的异常

package com.ray.ch17;

public class Test {

	public static void main(String[] args) {
		try {
			new Thread(new ThreadA()).start();
		} catch (Exception e) {
			System.out.println("捕捉到异常");
		}
	}
}

class ThreadA implements Runnable {

	@Override
	public void run() {
		throw new RuntimeException();
	}
}

输出:

Exception in thread "Thread-0" java.lang.RuntimeException
at com.ray.ch17.ThreadA.run(Test.java:18)
at java.lang.Thread.run(Thread.java:662)


3.问题:

在普通的情况下,我们可以顺利的捕捉到异常,但是如果在多线程的情况下,捕捉异常的方式其实不是上面的那种


4.解决方案

实现Thread.UncaughtExceptionHandler接口

(1)使用普通的方式来实现

package com.ray.ch17;

public class Test {

	public static void main(String[] args) {
		try {
			Thread thread = new Thread(new ThreadA());
			thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
			thread.start();
		} catch (Exception e) {
			System.out.println("捕捉到异常");
		}
	}
}

class ThreadA implements Runnable {

	@Override
	public void run() {
		throw new RuntimeException();
	}
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("捕捉到:" + t.getName() + "的异常");
	}
}

输出:

捕捉到:Thread-0的异常


(2)使用线程池的方式来实现

package com.ray.ch17;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Test {

	public static void main(String[] args) {
		ExecutorService executorService = Executors
				.newCachedThreadPool(new MyThreadFactory());
		executorService.execute(new ThreadA());
		executorService.shutdown();
	}
}

class ThreadA implements Runnable {

	@Override
	public void run() {
		throw new RuntimeException();
	}
}

class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		System.out.println("捕捉到:" + t.getName() + "的异常");
	}
}

class MyThreadFactory implements ThreadFactory {

	@Override
	public Thread newThread(Runnable r) {
		Thread thread = new Thread(r);
		thread.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
		return thread;
	}
}

输出:

捕捉到:Thread-0的异常


总结:这一章节比较详细的讨论了多线程的异常捕捉。


这一章节就到这里,谢谢。

-----------------------------------

目录


从头认识java-18.2 基本的线程机制(8)多线程的异常捕捉

标签:

原文地址:http://blog.csdn.net/raylee2007/article/details/50551142

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!