/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import java.awt.* ; 

2. import java.applet.* ; 

3. import java.awt.event.*; 

4.  

5. public class Threads 

6.     extends Applet 

7.     implements  Runnable,  MouseListener 

8.

9.   Thread task ; 

10.   boolean pause = false

11.   Label lbl, lbl2 ; 

12.    

13.   public void 

14.   init() 

15.   { 

16.     add ( lbl = new Label ( "+++++++++++++++++" ) ) ; 

17.     add ( lbl2 = new Label ( "#################" ) ) ; 

18.     addMouseListener ( this ) ; 

19.     setBackground ( Color.orange ) ; 

20.     validate () ; 

21.  

22.     task = new Thread ( this ) ; 

23.     task.start () ; 

24.  

25.     lbl2.setText ( "Thread started" ); 

26.   } 

27.  

28.   public void 

29.   run () 

30.   { 

31.     Color [] colors = { Color.cyan, Color.green, Color.pink }; 

32.     int i = 0

33.  

34.     Thread thisth = Thread.currentThread () ; 

35.  

36.     while ( task == thisth ) 

37.     { 

38.       if ( !pause ) 

39.       { 

40.         i = i % 3

41.         setBackground ( colors [i] ) ; 

42.         i++ ; 

43.         lbl.setText ( "Continued" )  ; 

44.       } 

45.       else 

46.       { 

47.         lbl.setText ( "Paused" )  ; 

48.       } 

49.       try

50.         Thread.sleep ( 1000 ) ; 

51.       } 

52.       catch (InterruptedException e) 

53.       { 

54.         lbl2.setText ( "Interrupted sleep" ) ; 

55.       } 

56.  

57.     } ///end while 

58.  

59.     setBackground ( Color.lightGray ) ; 

60.     lbl.setText ( "About to stop" )  ; 

61.   } 

62.  

63.  

64.   public void 

65.   mouseClicked ( MouseEvent ev ) 

66.   { 

67.     pause = !pause ; 

68.     if ( !pause ) 

69.       task.interrupt(); 

70.   } 

71.   public void 

72.   stop () 

73.   { 

74.     pause = true

75.     task.interrupt(); 

76.   } 

77.   public void 

78.   destroy () 

79.   { 

80.     task.interrupt(); 

81.     task = null

82.   } 

83.  

84.  

85.   public void mousePressed(MouseEvent e) {} 

86.   public void mouseReleased(MouseEvent e) {} 

87.   public void mouseEntered(MouseEvent e) {} 

88.   public void mouseExited(MouseEvent e) {} 

89.

90.