1 /* A class with one thread, implementing a Digital Clock */ 2 3 4 import java.awt.Graphics; 5 import java.awt.Font; 6 import java.util.Date; 7 8 public class DigitalThreads extends java.applet.Applet implements Runnable 9 { 10 Font theFont = new Font("TimesRoman",Font.BOLD,24); 11 Date theDate; 12 Thread runner; 13 14 // override the applet start method 15 public void start() 16 { 17 if (runner == null); 18 { 19 // construct an instance of a thread and use the run method 20 // from "this" applet 21 runner = new Thread(this); 22 runner.start(); // call the thread start method 23 } 24 } 25 26 // override the applet stop method 27 public void stop() 28 { 29 if (runner != null) 30 { 31 runner.stop(); // call the thread stop method 32 runner = null; 33 } 34 } 35 36 // provide a method run to be the body of the thread 37 // this method required by the runnable interface 38 public void run() 39 { 40 while (true) 41 { 42 theDate = new Date(); 43 // this method will call applet method update, 44 // which will call paint below 45 repaint(); 46 // current thread will sleep for 1 second 47 try { Thread.sleep(1000); } 48 catch (InterruptedException e) { } 49 } 50 } 51 52 // provide the applet paint method 53 public void paint(Graphics g) 54 { 55 g.setFont(theFont); 56 g.drawString(theDate.toString(),10,50); 57 } 58 } 59