從哪里發現默認行為?每個線程都屬于一個由 java.lang.ThreadGroup 類表示的線程組。顧名思義,線程組答應您將線程組合在一起。您可能是為了方便而將線程組合,例如,一個線程池中的所有線程都屬于組 X,而另一個池的所有線程則屬于組 Y,或者是為了訪問控制而將線程進行組合。組 X 中的線程無權訪問或改變組 Y 中的線程,除非它們都在同一線程組內(或在一個子組內)。
public class WindowDump { public static void main(String args[]) throws Exception { ThreadGroup group = new LoggingThreadGroup("Logger"); new Thread(group, "myThread") { public void run() { System.out.println(1 / 0); } }.start(); } }
private Filter makeFilter(String name) { Filter f = null; try { Class c = Class.forName(name); f = (Filter)c.newInstance(); } catch (Exception e) { if (name != null) { System.err.println("Unable to load filter: " + name); } } return f; }
private Formatter makeFormatter(String name) { Formatter f = null; try { Class c = Class.forName(name); f = (Formatter)c.newInstance(); } catch (Exception e) { f = new SimpleFormatter(); } return f; }
// Overridden abstract Handler methods
public void close() { }
public void flush() { }
/** * If record is loggable, format it and add it to window */ public void publish(LogRecord record) { String message = null; if (isLoggable(record)) { try { message = getFormatter().format(record); } catch (Exception e) { reportError(null, e, ErrorManager.FORMAT_FAILURE); return; } try { window.addLogInfo(message); } catch (Exception e) { reportError(null, e, ErrorManager.WRITE_FAILURE); } } } }
清單 6. LoggingWindow 的定義
import java.awt.*; import javax.swing.*;
public class LoggingWindow extends JFrame { private JTextArea textArea;
public LoggingWindow(String title, final int width, final int height) { super(title); EventQueue.invokeLater(new Runnable() { public void run() { setSize(width, height); textArea = new JTextArea(); JScrollPane pane = new JScrollPane(textArea); textArea.setEditable(false); getContentPane().add(pane); setVisible(true); } }); }
public void addLogInfo(final String data) { EventQueue.invokeLater(new Runnable() { public void run() { textArea.append(data); } }); } }