import java.awt.*; import java.io.*; import java.util.*; import javax.swing.*; public class ThreadTester extends JApplet implements Runnable { private JTextArea textArea = new JTextArea(); private Thread thread = new Thread(this); public void init() { JScrollPane scrollPane = new JScrollPane(textArea); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); getContentPane().add(scrollPane, BorderLayout.CENTER); thread.start(); } public void run() { System.out.println("\nCreating and starting thread 1\n"); textArea.append("Creating and starting thread 1\n\n"); textArea.setCaretPosition(textArea.getText().length()); T1 t1 = new T1(textArea); try { Thread.sleep(5000); } catch(InterruptedException ie) {} System.out.println("\nCreating and starting thread 2\n"); textArea.append("\nCreating and starting thread 2\n\n"); textArea.setCaretPosition(textArea.getText().length()); T2 t2 = new T2(textArea); try { Thread.sleep(5000); } catch(InterruptedException ie) {} System.out.println("\nKilling thread 1\n"); textArea.append("\nKilling thread 1\n\n"); textArea.setCaretPosition(textArea.getText().length()); t1.kill(); try { Thread.sleep(5000); } catch(InterruptedException ie) {} System.out.println("\nKilling thread 2\n"); textArea.append("\nKilling thread 2\n\n"); textArea.setCaretPosition(textArea.getText().length()); t2.kill(); } } class T1 extends Thread { private boolean alive = true; private JTextArea textArea; public T1(JTextArea textArea) { this.textArea = textArea; start(); } public void run() { while(alive) { System.out.println("Thread 1"); textArea.append("Thread 1\n"); textArea.setCaretPosition(textArea.getText().length()); try { sleep(1000); } catch(InterruptedException ie) {} } } public void kill() { alive = false; } } class T2 implements Runnable { private Thread t = new Thread(this); private boolean alive = true; private JTextArea textArea; public T2(JTextArea textArea) { this.textArea = textArea; t.start(); } public void run() { while(alive) { System.out.println("Thread 2"); textArea.append("Thread 2\n"); textArea.setCaretPosition(textArea.getText().length()); try { t.sleep(1000); } catch(InterruptedException ie) {} } } public void kill() { alive = false; } }