java多线程启动和停止

模拟一个电子时钟,它可以在任何时候被启动或者停止,并可以独立的运行。

1.定义一个Clock类。它继承Label类,并实现Runnable接口。这个类中有一个Thread类型的clocker域,以及start()和run()方法。在run()方法中,每隔一秒就把系统时间显示为label的文本。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Clock extends Label implements Runnable
{
   //定义Thread类型的clocker域
   public Thread clocker= null ;
   public Clock()
   {
     
     //初始化时,把label设置为当前系统时间
     //调用toString方法转化为String类型
     setText( new Date().toString());
   }
   //控制线程的启动
   public void start()
   {
     if (clocker== null )
     {
       //clocker通过Thread类构造方法得到的对象进行初始化,并将Clock类的当前对象作为参数
       clocker= new Thread( this );
       clocker.start();
     }
 
   }
   //控制线程的停止
   public void stop()
   {
     clocker= null ;
   }
   //实现Runnable接口中的run()方法
   public void run()
   {
     Thread currentThread=Thread.currentThread();
     //判断clocker是否是当前运行的线程
     while (clocker==currentThread)
     {
             setText( new Date().toString());
             try
            {   //休眠1s钟
                clocker.sleep( 1000 );
       }
       catch (InterruptedException ie)
       {
         System.out.println( "Thread error:" +ie);
       }
     }
   
   }
 
}

2.定义一个ClockFrame类。它继承Frame类,并实现ActionListener接口。在这个类中定义start和stop按钮来控制电子时钟的运行。并且这个类有一个Clock类的域,把这个Clock类对象添加到ClockFrame类中显示。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class ClockFrame extends Frame implements ActionListener
{
   private Button start= new Button( "Start" );
   private Button stop= new Button( "Stop" );
   private Clock c= new Clock();
   public ClockFrame()
   {
     super ( "电子时钟" );
     //设置窗体使用流式布局
     setLayout( new FlowLayout());
     //添加按钮并且为其注册监听器
     add(start);
     start.addActionListener( this );
     add(stop);
     stop.addActionListener( this );
     //使用继承WindowAdapter的匿名内部类来实现窗口的关闭
     addWindowListener( new WindowAdapter()
     {
       public void windowClosing(WindowEvent we)
       {System.exit( 0 );}
     });
     add(c);
     //使构件在窗口中得到合理的安排。
     pack();
     setVisible( true );
 
 
   }
   //通过调用Clock对象中的方法,实现对事件的响应。
   public void actionPerformed(ActionEvent ae)
   {
     if (ae.getSource()==start)
     {
       c.start();
     }
     else
       if (ae.getSource()==stop)
       c.stop();
 
   }
   public static void main(String[] args)
   {
     new ClockFrame();
   }
}

3、运行:

注:

需要导入的类:

?
1
2
3
import java.awt.*;
import java.awt.event.*;
import java.util.Date;

再给大家一个网友的做法,非常不错

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.awt.*; 
import javax.swing.*; 
import java.util.Date; 
  
/*TimeDemo.java
  * @src
public class TimeDemo extends JFrame implements Runnable { 
  
   Thread clock; 
     
   public static void main(String[] args) { 
   TimeDemo td = new TimeDemo(); 
   td.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //点击可见窗口右上角的红叉关闭 
   
     
   public TimeDemo(){ 
    super ( "雪地漫步---java多线程数字时钟" ); //继承父类构造方法,这里相当于Font("雪地漫步---java多线程数字时钟"); 
setTitle( "kk" );  //这个则是子类的 
    this .setFont( new Font( "Times New Roman" ,Font.BOLD, 60 ));  //设置字体大小 
    this .go();    //自定义go方法,用于以后开启线程 
    setBounds( 400 , 300 , 300 , 100 ); 
    this .setVisible( true ); 
  
  
    public void go(){ 
   stop(); 
    if (clock== null ){ 
   //线程执行的主题作为Thread类构造方法的参数。 
    clock= new Thread( this ); 
    clock.start();     //开启线程,实现run方法 
  
  
   public void run() { 
     while ( true )   //让线程一直进行 
  
//repain()方法是来控制Graphics类的paint()方法的,repain()方法执行一次,即让paint()方法执行一次 
       repaint();  
      try
       Thread.sleep( 1000 );   //参数是毫秒,1秒即1000毫秒 
      } catch (InterruptedException e){} 
    
   
  
   public void stop(){ 
    clock= null
  
  
   public void paint(Graphics g){ 
    String s= ""
    Date now= new Date(); 
    int hour=now.getHours();                      
    int minute=now.getMinutes(); 
    int second=now.getSeconds(); 
    s=hour+ ":" +minute+ ":" +second; 
    g.setColor(Color.green); 
    Dimension dim=getSize(); 
    g.fillRect( 0 , 0 , dim.width, dim.height); 
    g.setColor(Color.red); 
    g.drawString(s, 20 , 80 ); 
  
}

例子三:思路更加的巧妙,分享给大家

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.awt.BorderLayout;
  import java.awt.Canvas;
  import java.awt.Color;
  import java.awt.Font;
  import java.awt.Graphics;
  import java.sql.Date;
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  class Clock extends Canvas implements Runnable{
 
    /*
    http://ohgrateboy.blog.163.com我的博客
    */
 
    private static final long serialVersionUID = 3660124045489727166L;
    Thread t;
    JFrame frame= new JFrame();
    JPanel conPane;
    String time;
    int i= 0 ;
    Date timer;
    public Clock(){
      conPane=(JPanel)frame.getContentPane();
      conPane.setLayout( new BorderLayout());
      conPane.setSize( 280 , 40 );
      conPane.setBackground(Color.white);
      conPane.add( this ,BorderLayout.CENTER);
      t= new Thread( this );        //实例化线
     t.start();    //调用线程
     
      frame.setVisible( true );
      frame.setSize( 300 , 150 );
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    public void run(){
 
      while ( true ){
 
      try {
 
        Thread.sleep( 1000 );          //休眠1秒钟
 
     } catch (InterruptedException e){
 
        System.out.println( "异常" );
      }
      this .repaint( 100 );
 
    }
 
    }
 
    public void paint(Graphics g){
 
      Font f= new Font( "宋体" ,Font.BOLD, 16 );
 
      SimpleDateFormat SDF= new SimpleDateFormat( "yyyy'年'MM'月'dd'日'HH:mm:ss" ); //格式化时间显示类型
     Calendar now=Calendar.getInstance();
 
      time=SDF.format(now.getTime());    //得到当前日期和时间
     g.setFont(f);
 
      g.setColor(Color.orange);
 
      g.drawString(time, 45 , 25 );
 
    }
    public static void main(String args[]){
      new Clock();
    }
 
  }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值