Java multi threaded programming electronic clock

  • 2020-04-01 04:26:42
  • OfStack

  Simulate an electronic clock that can be started or stopped at any time and can run independently.

1. Define a Clock class. It inherits the Label class and implements the Runnable interface. This class has a clocker field of type Thread, along with the start () and run () methods. In the run () method, the system time is displayed every second as the text of the label.


class Clock extends Label implements Runnable
{
  //Define a clocker field of type Thread
  public Thread clocker=null;
  public Clock()
  {
    
    //When initialized, set the label to the current system time
    //Call the toString method to convert toString type
    setText(new Date().toString());
  }
  //Controls the start of a thread
  public void start()
  {
    if(clocker==null)
    {
      //Clocker initializes the object from the Thread class constructor and takes the current object of the Clock class as an argument
      clocker=new Thread(this);
      clocker.start();
    }

  }
  //Controls the stopping of threads
  public void stop()
  {
    clocker=null;
  }
  //Implement the run () method in the Runnable interface
  public void run()
  {
    Thread currentThread=Thread.currentThread();
    //Determines if clocker is the currently running thread
    while(clocker==currentThread)
    {
            setText(new Date().toString());
            try
           {   //Dormancy 1 s clock
               clocker.sleep(1000);
      }
      catch (InterruptedException ie)
      {
        System.out.println("Thread error:"+ie);
      }
    }
  
  }

}

2. Define a ClockFrame class. It inherits the Frame class and implements the ActionListener interface. Define the start and stop buttons in this class to control the running of the electronic clock. And this class has a field of Clock class, add this Clock class object to the ClockFrame class to display.


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(" Electronic clock ");
    //Sets the form to use a streaming layout
    setLayout(new FlowLayout());
    //Add a button and register a listener for it
    add(start);
    start.addActionListener(this);
    add(stop);
    stop.addActionListener(this);
    //Use anonymous inner classes that inherit from the WindowAdapter to close the window
    addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent we)
      {System.exit(0);}
    });
    add(c);
    //So that the components in the window to get a reasonable arrangement.
    pack();
    setVisible(true);


  }
  //The response to the event is achieved by calling a method in the Clock object.
  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. Operation:

Note:

Classes to import:


import java.awt.*;
import java.awt.event.*;
import java.util.Date;

Give you a netizen's practice again, very good


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); //Click the Red Cross in the upper right corner of the visible window to close
   }  
    
  public TimeDemo(){  
   super(" Snow stroll ---java Multithreaded digital clock "); //Inherited the parent constructor, in this case the Font(" snow walk - Java multithreaded digital clock ");
setTitle("kk");  //This one is subclassed
   this.setFont(new Font("Times New Roman",Font.BOLD,60));  //Set the font size
   this.go();    //Custom go method for starting threads later
   setBounds(400,300,300,100);  
   this.setVisible(true);  
  }  
 
   public void go(){  
  stop();  
   if(clock==null){  
  //The topic that the Thread executes takes as an argument to the Thread class constructor.
   clock=new Thread(this);  
   clock.start();     //Start the thread and implement the run method
  }  
}  
 
  public void run() {  
    while(true)   //Keep the thread running
  {  
//The repain() method is used to control the paint() method of the Graphics class, and the repain() method executes once, letting the paint() method execute once
      repaint();   
     try{  
      Thread.sleep(1000);   //The parameter is milliseconds,1 second is 1000 milliseconds
     }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);  
  }  
} 

Example 3: more ingenious ideas, share with you


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 My blog 
   */

   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);        //Instantiation line
    t.start();    //The calling thread
    
     frame.setVisible(true);
     frame.setSize(300, 150);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }

   public void run(){

     while(true){

     try{

       Thread.sleep(1000);          //Sleep for 1 second

    }catch(InterruptedException e){

       System.out.println(" abnormal ");
     }
     this.repaint(100);

   }

   }

   public void paint(Graphics g){

     Font f=new Font(" Song typeface ",Font.BOLD,16);

     SimpleDateFormat SDF=new SimpleDateFormat("yyyy' years 'MM' month 'dd' day 'HH:mm:ss");//Format time displays the type
    Calendar now=Calendar.getInstance();

     time=SDF.format(now.getTime());    //Get the current date and time
    g.setFont(f);

     g.setColor(Color.orange);

     g.drawString(time,45,25);

   }
   public static void main(String args[]){
     new Clock();
   }

 } 


Related articles: