Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.javarush.test.level16.lesson13.bonus03;
- /* Отдебажим все на свете
- Разобраться, что делает програма.
- Почитать про UncaughtExceptionHandler - это важно.
- Еще раз внимательно посмотреть программу.
- Разобраться - продебажить - почему наш OurUncaughtExceptionHandler не срабатывает.
- Исправить ошибку, т.е. все должно работать. :)
- Ожидаемый результат в произвольном порядке:
- Нить 1: My exception message
- Нить 2: My exception message
- */
- public class Solution {
- public static Thread.UncaughtExceptionHandler handler = new OurUncaughtExceptionHandler();
- public static void main(String[] args) {
- TestedThread commonThread = new TestedThread(handler);
- /*
- * 1. У TestedThread есть конструктор, которому передается
- * UncaughtExceptionHandler как аргумент; sets new OurUncaughtExceptionHendler;
- * new OurUncaughtExceptionHandler (System.out.println(t.getName() + ": " + e.getMessage());)//должно ловить.
- * при создании TesetedThread выбрасывает uncaught exception,
- *2.
- * */
- Thread threadA = new Thread(commonThread, "Нить 1");//как аргумент commonThread
- Thread threadB = new Thread(commonThread, "Нить 2");
- threadA.start();
- threadB.start();
- threadA.setUncaughtExceptionHandler(handler);
- threadB.setUncaughtExceptionHandler(handler);
- threadA.interrupt();
- threadB.interrupt();
- }
- public static class TestedThread extends Thread {
- /*------------конструктор------------------*/
- public TestedThread(UncaughtExceptionHandler handler) {
- setUncaughtExceptionHandler(handler);
- start();
- }
- /*---------------------------------------------------*/
- public void run() {
- try {
- Thread.sleep(3000);
- } catch (InterruptedException x) {
- throw new RuntimeException("My exception message"); //this thread terminates due to uncaught exception
- } //
- }
- /*----------------------------------------------------*/
- }
- public static class OurUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
- @Override
- public void uncaughtException(Thread t, Throwable e) /*passing thread (t) and exception (e) as arguments*/
- {
- System.out.println(t.getName() + ": " + e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement